Hardware components | ||||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
Software apps and online services | ||||||
| ||||||
| ||||||
| ||||||
|
In this project you will see how to automate various gadgets of your home and room. You will be able to control the lights, fan, air conditioning, curtains, locks and TV. Both from Amazon Alexa and Mobile Phone (without using any Android or IOS app).
Setup and TV ControlsThis requires Raspberry PI 3 Model B with latest Raspbian OS installed through NOOBS. The following link https://www.raspberrypi.org/learning/software-guide/quickstart/ provides the method to install the latest updated OS.
Once Raspberry OS is setup then connect the IR as given below
Connect the Raspberry with a keyboard or mouse and enable VNC so you can remotely access the Raspberry.
Open the terminal and execute the following commands:
sudo apt-get install lirc
sudo chmod a+w /var/run/lirc/
sudo chmod a+w /var/run/lirc/lircd
Add this to your /etc/modules file:
lirc_dev
edit /etc/lirc/lirc_options.conf and set
driver = devinput
to
driver = default
Create your /etc/lirc/hardware.conf file to:
########################################################
# /etc/lirc/hardware.conf
#
# Arguments which will be used when launching lircd
LIRCD_ARGS="--uinput"
# Don't start lircmd even if there seems to be a good config file
# START_LIRCMD=false
# Don't start irexec, even if a good config file seems to exist.
# START_IREXEC=false
# Try to load appropriate kernel modules
LOAD_MODULES=true
# Run "lircd --driver=help" for a list of supported drivers.
DRIVER="default"
# usually /dev/lirc0 is the correct setting for systems using udev
DEVICE="/dev/lirc0"
MODULES="lirc_rpi"
# Default configuration files for your hardware if any
LIRCD_CONF=""
LIRCMD_CONF=""
########################################################
Edit your /boot/config.txt file and add:
dtoverlay=lirc-rpi,gpio_in_pin=23,gpio_out_pin=22
Goto www.lirc.org website download the configuration of the device and model you need to automate just like I have got for my Samsung TV
begin remote
name samsung
bits 16
flags SPACE_ENC|CONST_LENGTH
eps 30
aeps 100
header 4511 4553
one 505 1734
zero 505 614
ptrail 505
pre_data_bits 16
pre_data 0xE0E0
gap 107878
min_repeat 1
# suppress_repeat 1
# uncomment to suppress unwanted repeats
toggle_bit_mask 0x0
begin codes
KEY_POWER 0x40BF
KEY_TUNER 0x807F
KEY_MUTE 0xF00F
KEY_VOLUMEUP 0xE01F
KEY_VOLUMEDOWN 0xD02F
KEY_SELECT 0x16E9
KEY_UP 0x06F9
KEY_DOWN 0x8679
KEY_LEFT 0xA659
KEY_RIGHT 0x46B9
end codes
end remote
Add the the configutration in /etc/lirc/lircd.conf
Reboot
Once rebooted you can check the IR simulation with following command on the terminal by pointing the IR to the device.
irsend send_once samsung KEY_POWER
Setup the Wifi and connect to your home router. Please note you will require internet on the Raspberry and the router should not block the port that you have setup on your cloud server. On cloud server create a server socket program (java program provided in the code section) that accepts the connection from raspberry pi and also performs the CGI interface for Lambda function for the Alexa Smart Home Skill.
The Java code in code section for client is method by which the Raspberry PI mediates (acts as hub) between the Gadgets and Server.
In the JAVA code we are reading a parameter file which looks like this
tvmodel=samsung
settopboxmodel=tatasky
kc_0000004=Bedroom,Bed Right,Bed Left,Ceiling,Vestibule,Bathroom
channels=ABP News:309,BBC New:890,Star Plus:560
TV Model and Set Top Box is identified from the parameter. They can also be hardcoded in the program.
Switchboards are identified by kc_
And the channel numbers and names are mapped for IR simulation.
Curtain Controls
For controlling the curtains the following material would be required.
Stepper Motor
TB6560 Controller
Arduino UNO
and the NodeMCU circuit explained later in next section of this project.
The Stepper Motor is Connected as shown in the following diagram.
The image below explains how physically the Arduino controls two motors for two curtains.
if (currentState != previousState && currentState == HIGH){
previousState = currentState;
digitalWrite(ENABLE_PIN1, HIGH);
delay(100);
digitalWrite(DIR_PIN1, HIGH);
delay(100);
digitalWrite(ENABLE_PIN1, LOW);
digitalWrite(ENABLE_PIN2, HIGH);
delay(100);
digitalWrite(DIR_PIN2, HIGH);
delay(100);
digitalWrite(ENABLE_PIN2, LOW);
steps = 0;
}
if (currentState != previousState && currentState == LOW) {
previousState = currentState;
digitalWrite(ENABLE_PIN1, HIGH);
delay(100);
digitalWrite(DIR_PIN1, LOW);
delay(100);
digitalWrite(ENABLE_PIN1, LOW);
digitalWrite(ENABLE_PIN2, HIGH);
delay(100);
digitalWrite(DIR_PIN2, LOW);
delay(100);
digitalWrite(ENABLE_PIN2, LOW);
steps = 0;
}
When PIN 8 of arduino is toggled by the NodeMCU the motors operate in clockwise or anti clock wise direction.
The above build for Motor and the rails can be found at http://openbuildspartstore.com/v-slot-nema-17-linear-actuator-bundle-belt-driven/
I have used NEMA 23 instead of NEMA 17 and the size of the V Slot rail depends on the size of window and/or curtain.
Switch ControlsThe circuit for the switch control is uploaded in the schematics section. The circuit operates the relay from NodeMCU as shown below
The code can be modified to use momentary switches, ordinary toggle switches or even two way switches.
12V to 5V circuit explained here
Code for NodeMCU
Before you can write the code for NodeMCU, you need to set it up in the Arduino Editor. Follow the steps to do this.
1. Go to preference section from Tools in Arduino Editor and add the URL in Additional Boards Manager URL.
2. From the boards manager search for NodeMCU and install the latest version.
3. Install cp2102 driver from https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers
Now you are ready to code for NodeMCU depending on the module you are using.
Door Lock ControlsI have used a electromagnetic lock for this purpose. You can use any other mechanism such a solenoid. The only difference is that the code is to be modified so that the door does not remain open for more than 8-10 seconds and closes automatically.
The following code explains how it is handled.
if (server.argName(i) == "out4") { // LOCK OUTPUT
if (server.arg(i) == "0") {
digitalWrite(out4, LOW);
status = status + " 4=OFF";
state4 = 0;
unlockedtime = millis(); // time variable is set when the door is unlocked
} else {
digitalWrite(out4, HIGH);
status = status + " 4=ON";
state4 = 1;
}
EEPROM.write(4, state4);
}
And in the loop section modify to following
if (millis() - unlockedtime > 8000) {
digitalWrite(out4, HIGH); // THIS IS LOCKED AUTOMATICALLY AFTER 8 SECONDS
}
AC and Thermostat ControlFor Thermostat we have used
Node MCU
SSD 1306 oled display
APDS 9960 Gesture Sensor
DS18B20 Temperature Sensor
The connections are as follows as we will be using the Adafruit Library for oled display and Sparkfun Library for Gesture Sensing
Adafruit_SSD1306 display
(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);
DC —— D0
RES —— D3
SDA —— D4
SCL —— D5
SPARKFUN GESTURE
SCL —— D1
SDA —— D2
From manage libraries install Adafruit and Sparkfun Libraries as shown below
You will may also have to update the OneWire Library.
A very good example to use DS18B20 can be found here https://create.arduino.cc/projecthub/TheGadgetBoy/ds18b20-digital-temperature-sensor-and-arduino-9cc806
In this automation switching on and off the AC is by waving right and left. And to increase and decrease the set temperature wave up and down.
Enjoy.
Mobile Page GUIThe java program on raspberry also implements WebServer. So you can access the WebServer by "yourraspberrypi.ip.addresss:/8081"
And you will be able to control all your gadgets from Mobile Page
You can also control Raspberry Keyboard and Mouse from Mobile Page. Hope my efforts in doing it will be appreciated by all of you.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
public class AlexaClient {
final openingPage page;
AlexaClient(final openingPage page) {
this.page = page;
Timer timer = new Timer();
timer.schedule(new loop(), 500, 60000);
}
private class loop extends TimerTask {
@Override
public void run() {
try {
Socket client = new Socket("yourserveroncloud", 54321);
System.out.println("Connected To yourserveroncloud");
InputStream is = client.getInputStream();
OutputStream os = client.getOutputStream();
os.write(license.getBytes());
os.flush();
byte[] bytes = new byte[64];
client.setKeepAlive(true);
client.setSoTimeout(60000);
int numberOfBytes = 0;
try {
while (true) {
try {
numberOfBytes = is.read(bytes);
} catch (Exception re) {
numberOfBytes = 0;
}
if (numberOfBytes < 1) {
try {
os.write("OM".getBytes());
continue;
} catch (Exception oe) {
oe.printStackTrace();
break;
}
} else {
String cmd = new String(bytes, 0, numberOfBytes);
System.out.println(cmd);
processCommand("cmd="+cmd);
}
}
os.close();
is.close();
client.close();
} catch (Exception ex) {
ex.printStackTrace();
try {
os.close();
is.close();
client.close();
} catch (Exception e) {
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private String processCommand(String query) {
try {
int i = query.indexOf("cmd=");
if (i >= 0) {
if (query.indexOf("&") > i) {
page.pageEvent(query.substring(i+4, query.indexOf("&")));
} else {
page.pageEvent(query.substring(i+4));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return page.currentApp;
}
}
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MouseInfo;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class openingPage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JDesktopPane desktopPane;
private Image imgBackground;
private Image imgInfo;
public String currentApp = "";
private Process process;
private Robot robot;
private int screenWidth;
private int screenHeight;
private String path;
private String tvmodel;
private String settopboxmodel;
private JLabel lblGuest;
private class channel {
public String channelNo;
public String channelName;
channel() {
channelNo = "";
channelName = "";
}
}
ArrayList<channel> channels;
private class switchBoard {
public String boardId;
public String boardName;
public String boardIP;
public String switch1;
public String switch1State;
public String switch2;
public String switch2State;
public String switch3;
public String switch3State;
public String switch4;
public String switch4State;
public String switch5;
public String switch5State;
switchBoard() {
boardId = "kc_0000000";
boardIP = "0.0.0.0";
boardName = "Switch Board";
switch1 = "Switch 1";
switch1State = "0";
switch2 = "Switch 2";
switch2State = "0";
switch3 = "Switch 3";
switch3State = "0";
switch4 = "Switch 4";
switch4State = "0";
switch5 = "Switch 5";
switch5State = "0";
}
}
ArrayList<switchBoard> switchBoards;
openingPage() {
try {
switchBoards = new ArrayList<switchBoard>();
channels = new ArrayList<channel>();
File jarFile = new File(
openingPage.class.getProtectionDomain().getCodeSource().getLocation().toURI());
path = jarFile.getParentFile().getAbsolutePath();
System.out.println(path);
File paramfile = new File(path + "/SmartTV.param");
BufferedReader br = new BufferedReader(new FileReader(paramfile));
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
String[] params = inputLine.split("=");
if (params[0].equals("tvmodel")) {
tvmodel = params[1];
}
if (params[0].equals("settopboxmodel")) {
settopboxmodel = params[1];
}
if (params[0].startsWith("kc_")) {
switchBoards.add(new switchBoard());
switchBoards.get(switchBoards.size()-1).boardId = params[0];
switchBoards.get(switchBoards.size()-1).boardName = params[1].split(",")[0];
switchBoards.get(switchBoards.size()-1).switch1 = params[1].split(",")[1];
switchBoards.get(switchBoards.size()-1).switch2 = params[1].split(",")[2];
switchBoards.get(switchBoards.size()-1).switch3 = params[1].split(",")[3];
switchBoards.get(switchBoards.size()-1).switch4 = params[1].split(",")[4];
switchBoards.get(switchBoards.size()-1).switch5 = params[1].split(",")[5];
}
if (params[0].equals("channels")) {
String[] listChannels = params[1].split("\\|");
for (int i = 0; i < listChannels.length; ++i) {
channels.add(new channel());
channels.get(i).channelName = listChannels[i].split(":")[0];
channels.get(i).channelNo = listChannels[i].split(":")[1];
System.out.println(listChannels[i].split(":")[0] + " " + listChannels[i].split(":")[1]);
}
}
}
br.close();
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
for (; n.hasMoreElements();) {
NetworkInterface e = n.nextElement();
Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements();)
{
InetAddress addr = a.nextElement();
System.out.println(" " + addr.getHostAddress());
if (addr.getHostAddress().contains(":") || addr.getHostAddress().contains("127.0.0.1")) {
continue;
}
//host = addr.getHostAddress();
}
}
} catch(Exception ex) {
}
screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
setSize(screenWidth, screenHeight);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setUndecorated(true);
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
try {
robot = new Robot();
robot.mouseMove((screenWidth/2), (screenHeight-300));
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
imgBackground = ImageIO.read(new File("desktop.jpg"));
imgBackground = imgBackground.getScaledInstance(screenWidth, screenHeight, java.awt.Image.SCALE_SMOOTH);
imgInfo = ImageIO.read(openingPage.class.getResource("/resources/info.png"));
imgInfo = imgInfo.getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
desktopPane = new JDesktopPane() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(imgBackground, 0, 0, null);
}
@Override
public Dimension getPreferredSize() {
return Toolkit.getDefaultToolkit().getScreenSize();
}
};
try {
setContentPane(desktopPane);
} catch (Exception e) {
e.printStackTrace();
}
setVisible(true);
new JSONServer(this);
new AlexaClient(this);
}
public String pageEvent(String event) {
if (event.startsWith("kc_")) {
//kc_0000001:11*out1:0*out2:0*out3:0*out4:0*out5:0
if (event.indexOf("*") > 0) {
String[] switchState = event.split("\\*");
System.out.println(switchState[0].split(":")[0]);
for (int i = 0; i < switchBoards.size(); ++i) {
if (switchBoards.get(i).boardId.equals(switchState[0].split(":")[0])) {
switchBoards.get(i).boardIP = switchState[0].split(":")[1];
switchBoards.get(i).switch1State = switchState[1].split(":")[1];
switchBoards.get(i).switch2State = switchState[2].split(":")[1];
switchBoards.get(i).switch3State = switchState[3].split(":")[1];
switchBoards.get(i).switch4State = switchState[4].split(":")[1];
switchBoards.get(i).switch5State = switchState[5].split(":")[1];
}
}
} else {
for (int i = 0; i < switchBoards.size(); ++i) {
if (switchBoards.get(i).boardId.equals(event.split(":")[0])) {
if (!switchBoards.get(i).boardIP.equals("0.0.0.0")) {
try {
String switchState = "1";
if (event.split(":")[1].equals("out1")) {
if (switchBoards.get(i).switch1State.equals("0")) {
switchBoards.get(i).switch1State = "1";
} else {
switchBoards.get(i).switch1State = "0";
}
switchState = switchBoards.get(i).switch1State;
}
if (event.split(":")[1].equals("out2")) {
if (switchBoards.get(i).switch2State.equals("0")) {
switchBoards.get(i).switch2State = "1";
} else {
switchBoards.get(i).switch2State = "0";
}
switchState = switchBoards.get(i).switch2State;
}
if (event.split(":")[1].equals("out3")) {
if (switchBoards.get(i).switch3State.equals("0")) {
switchBoards.get(i).switch3State = "1";
} else {
switchBoards.get(i).switch3State = "0";
}
switchState = switchBoards.get(i).switch3State;
}
if (event.split(":")[1].equals("out4")) {
if (switchBoards.get(i).switch4State.equals("0")) {
switchBoards.get(i).switch4State = "1";
} else {
switchBoards.get(i).switch4State = "0";
}
switchState = switchBoards.get(i).switch4State;
}
if (event.split(":")[1].equals("out5")) {
if (switchBoards.get(i).switch5State.equals("0")) {
switchBoards.get(i).switch5State = "1";
} else {
switchBoards.get(i).switch5State = "0";
}
switchState = switchBoards.get(i).switch5State;
}
String httpURL = String.format("http://%s/cmd?%s=%s", switchBoards.get(i).boardIP, event.split(":")[1], switchState);
System.out.println(httpURL);
URL myurl = new URL(httpURL);
HttpURLConnection con = (HttpURLConnection) myurl.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(99999);
con.setReadTimeout(0);
con.setDoOutput(true);
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String xml = "";
String inputLine;
while ((inputLine = in.readLine()) != null) {
xml += inputLine;
}
in.close();
isr.close();
ins.close();
con.disconnect();
System.out.println(xml);
break;
} catch (Exception e) {
e.printStackTrace();
}
}
}
//kc_0000001_4_ON
if (event.substring(0, 10).equals(switchBoards.get(i).boardId) && event.split("_").length == 4) {
if (!switchBoards.get(i).boardIP.equals("0.0.0.0")) {
try {
String switchState = "1";
if (event.split("_")[2].equals("1")) {
if (event.split("_")[3].equals("ON")) {
switchBoards.get(i).switch1State = "1";
} else {
switchBoards.get(i).switch1State = "0";
}
switchState = switchBoards.get(i).switch1State;
}
if (event.split("_")[2].equals("2")) {
if (event.split("_")[3].equals("ON")) {
switchBoards.get(i).switch2State = "1";
} else {
switchBoards.get(i).switch2State = "0";
}
switchState = switchBoards.get(i).switch2State;
}
if (event.split("_")[2].equals("3")) {
if (event.split("_")[3].equals("ON")) {
switchBoards.get(i).switch3State = "1";
} else {
switchBoards.get(i).switch3State = "0";
}
switchState = switchBoards.get(i).switch3State;
}
if (event.split("_")[2].equals("4")) {
if (event.split("_")[3].equals("ON")) {
switchBoards.get(i).switch4State = "1";
} else {
switchBoards.get(i).switch4State = "0";
}
switchState = switchBoards.get(i).switch4State;
}
if (event.split("_")[2].equals("5")) {
if (event.split("_")[3].equals("ON")) {
switchBoards.get(i).switch5State = "1";
} else {
switchBoards.get(i).switch5State = "0";
}
switchState = switchBoards.get(i).switch5State;
}
if (event.split("_")[2].equals("ALL")) {
if (event.split("_")[3].equals("ON")) {
switchBoards.get(i).switch1State = "1";
switchBoards.get(i).switch2State = "1";
switchBoards.get(i).switch3State = "1";
switchBoards.get(i).switch4State = "1";
switchBoards.get(i).switch5State = "1";
} else {
switchBoards.get(i).switch1State = "0";
switchBoards.get(i).switch2State = "0";
switchBoards.get(i).switch3State = "0";
switchBoards.get(i).switch4State = "0";
switchBoards.get(i).switch5State = "0";
}
switchState = switchBoards.get(i).switch1State;
}
for (int d = 1; d <= 5; ++d) {
if (event.split("_")[2].equals("ALL") || Integer.parseInt(event.split("_")[2]) == d) {
String httpURL = String.format("http://%s/cmd?out%d=%s", switchBoards.get(i).boardIP, d, switchState);
System.out.println(httpURL);
URL myurl = new URL(httpURL);
HttpURLConnection con = (HttpURLConnection) myurl.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(99999);
con.setReadTimeout(0);
con.setDoOutput(true);
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String xml = "";
String inputLine;
while ((inputLine = in.readLine()) != null) {
xml += inputLine;
}
in.close();
isr.close();
ins.close();
con.disconnect();
System.out.println(xml);
}
}
break;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
if (event.equals("getSwitchBoards")) {
String listOfSwitchBoards = "";
for (int i = 0; i < switchBoards.size(); ++i) {
if (i > 0) {
listOfSwitchBoards += ("|" + switchBoards.get(i).boardId);
} else {
listOfSwitchBoards += switchBoards.get(i).boardId;
}
listOfSwitchBoards += ("," + switchBoards.get(i).boardName);
listOfSwitchBoards += ("," + switchBoards.get(i).switch1 + ":" + switchBoards.get(i).switch1State);
listOfSwitchBoards += ("," + switchBoards.get(i).switch2 + ":" + switchBoards.get(i).switch2State);
listOfSwitchBoards += ("," + switchBoards.get(i).switch3 + ":" + switchBoards.get(i).switch3State);
listOfSwitchBoards += ("," + switchBoards.get(i).switch4 + ":" + switchBoards.get(i).switch4State);
listOfSwitchBoards += ("," + switchBoards.get(i).switch5 + ":" + switchBoards.get(i).switch5State);
}
return listOfSwitchBoards;
}
if (event.equals("close")) {
try {
doType(KeyEvent.VK_CONTROL, KeyEvent.VK_W);
if (currentApp.equals("mp4")) {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","pkill omxplayer"});
}
if (currentApp.equals("pdf")) {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","pkill xpdf"});
}
robot.mouseMove((screenWidth/2), (screenHeight-300));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (event.equals("tvpower")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + tvmodel + " KEY_POWER"});
} catch (Exception ex) {
ex.printStackTrace();
}
return "OK";
}
if (event.equals("tvsource")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + tvmodel + " KEY_TUNER"});
} catch (Exception ex) {
ex.printStackTrace();
}
return "OK";
}
if (event.equals("tvleft") || event.equals("tvprevious")) {
if (currentApp.equals("pdf")) {
robot.keyPress(KeyEvent.VK_UP);
robot.keyRelease(KeyEvent.VK_UP);
} else {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + tvmodel + " KEY_TUNER"});
Thread.sleep(1000);
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + tvmodel + " KEY_LEFT"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
return "OK";
}
if (event.equals("tvright") || event.equals("tvnext")) {
if (currentApp.equals("pdf")) {
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
} else {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + tvmodel + " KEY_TUNER"});
Thread.sleep(1000);
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + tvmodel + " KEY_RIGHT"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
return "OK";
}
if (event.equals("tvmute")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + tvmodel + " KEY_MUTE"});
} catch (Exception ex) {
ex.printStackTrace();
}
return "OK";
}
if (event.equals("tvvolumeup")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + tvmodel + " KEY_VOLUMEUP"});
} catch (Exception ex) {
ex.printStackTrace();
}
return "OK";
}
if (event.equals("tvvolumedown")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + tvmodel + " KEY_VOLUMEDOWN"});
} catch (Exception ex) {
ex.printStackTrace();
}
return "OK";
}
if (event.startsWith("tvchannel_")) {
String channelToChange = event.split("_")[1];
String channelNo = channelToChange;
for (int i = 0; i < channels.size(); ++i) {
if (channels.get(i).channelName.toUpperCase().equals(channelToChange.toUpperCase())) {
channelNo = channels.get(i).channelNo;
}
}
System.out.println("Sending " + channelNo);
for (int i = 0; i < channelNo.length(); ++i) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_" + channelNo.substring(i, i+1)});
Thread.sleep(500);
} catch (Exception ex) {
ex.printStackTrace();
}
}
return "OK";
}
if (event.equals("remotepower")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_POWER"});
} catch (Exception ex) {
ex.printStackTrace();
}
return "OK";
}
if (event.equals("remotemute")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_MUTE"});
} catch (Exception ex) {
ex.printStackTrace();
}
return "OK";
}
if (event.equals("remoteguide")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_MENU"});
} catch (Exception ex) {
ex.printStackTrace();
}
return "OK";
}
if (event.equals("remoteok")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_OK"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (event.equals("remoteup")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_UP"});
} catch (Exception ex) {
ex.printStackTrace();
}
return "OK";
}
if (event.equals("remotedown")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_DOWN"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (event.equals("remoteback")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_BACK"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (event.equals("remote1")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_1"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (event.equals("remote2")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_2"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (event.equals("remote3")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_3"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (event.equals("remote4")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_4"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (event.equals("remote5")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_5"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (event.equals("remote6")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_6"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (event.equals("remote7")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_7"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (event.equals("remote8")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_8"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (event.equals("remote9")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_9"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (event.equals("remote0")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_0"});
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (event.equals("remotevolumeup")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_VOLUMEUP"});
} catch (Exception ex) {
ex.printStackTrace();
}
return "OK";
}
if (event.equals("remotevolumedown")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_VOLUMEDOWN"});
} catch (Exception ex) {
ex.printStackTrace();
}
return "OK";
}
if (event.equals("remotechannelup")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_CHANNELUP"});
} catch (Exception ex) {
ex.printStackTrace();
}
return "OK";
}
if (event.equals("remotechanneldown")) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","irsend send_once " + settopboxmodel + " KEY_CHANNELDOWN"});
} catch (Exception ex) {
ex.printStackTrace();
}
return "OK";
}
if (event.equals("google")) {
try {
if (process != null && process.isAlive()) process.destroy();
robot.mouseMove(screenWidth/2, screenHeight/2);
process = Runtime.getRuntime()
.exec(new String[] {"/bin/bash", "-c", "chromium-browser --app=https://www.google.com --incognito --start-maximized"});
currentApp = "web";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "web";
}
if (event.equals("youtube")) {
try {
if (process != null && process.isAlive()) process.destroy();
robot.mouseMove(screenWidth/2, screenHeight/2);
process = Runtime.getRuntime()
.exec(new String[] {"/bin/bash", "-c", "chromium-browser --app=https://www.youtube.com --incognito --start-maximized"});
currentApp = "web";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "web";
}
if (event.equals("tunein")) {
try {
if (process != null && process.isAlive()) process.destroy();
robot.mouseMove(screenWidth/2, screenHeight/2);
process = Runtime.getRuntime()
.exec(new String[] {"/bin/bash", "-c", "chromium-browser --app=https://www.tunein.com --incognito --start-maximized"});
currentApp = "web";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "web";
}
if (event.equals("netflix")) {
try {
if (process != null && process.isAlive()) process.destroy();
robot.mouseMove(screenWidth/2, screenHeight/2);
process = Runtime.getRuntime()
.exec(new String[] {"/bin/bash", "-c", "chromium-browser --app=https://www.netflix.com --start-maximized"});
currentApp = "web";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "web";
}
if (event.equals("amazonprime")) {
try {
if (process != null && process.isAlive()) process.destroy();
robot.mouseMove(screenWidth/2, screenHeight/2);
process = Runtime.getRuntime()
.exec(new String[] {"/bin/bash", "-c", "chromium-browser --app=https://www.primevideo.com --start-maximized"});
currentApp = "web";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "web";
}
if (event.equals("whatsapp")) {
try {
if (process != null && process.isAlive()) process.destroy();
robot.mouseMove(screenWidth/2, screenHeight/2);
process = Runtime.getRuntime()
.exec(new String[] {"/bin/bash", "-c", "chromium-browser --app=https://web.whatsapp.com --incognito --start-maximized"});
currentApp = "web";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "web";
}
if (event.equals("irdmenu")) {
try {
if (process != null && process.isAlive()) process.destroy();
robot.mouseMove(screenWidth/2, screenHeight/2);
process = Runtime.getRuntime()
.exec(new String[] {"/bin/bash", "-c", "xpdf -fullscreen irdmenu.pdf"});
currentApp = "pdf";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "pdf";
}
if (event.equals("showplaces")) {
try {
if (process != null && process.isAlive()) process.destroy();
robot.mouseMove(screenWidth/2, screenHeight/2);
process = Runtime.getRuntime()
.exec(new String[] {"/bin/bash", "-c", "omxplayer places.mp4"});
currentApp = "mp4";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "mp4";
}
if (event.startsWith("mouse_") ) {
if (event.split("_").length == 3) {
String xOffset = event.split("_")[1];
String yOffset = event.split("_")[2];
robot.mouseMove((int) MouseInfo.getPointerInfo().getLocation().getX() + (int) Double.parseDouble(xOffset), (int) MouseInfo.getPointerInfo().getLocation().getY() + (int) Double.parseDouble(yOffset));
} else {
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
return "OK";
}
if (event.startsWith("go_") ) {
if (event.split("_").length == 2) {
String text = event.split("_")[1];
if (text.equals("<<")) {
robot.keyPress(KeyEvent.VK_BACK_SPACE);
robot.keyRelease(KeyEvent.VK_BACK_SPACE);
return "OK";
}
if (text.equals(">>")) {
text = "\n";
}
if (text.equals("us")) {
text = "_";
}
if (text.equals("amp")) {
text = "&";
}
if (text.equals("at")) {
text = "@";
}
if (text.equals("hash")) {
text = "#";
}
if (text.equals("per")) {
text = "%";
}
if (text.equals("carat")) {
text = "^";
}
if (text.equals("curlleft")) {
text = "{";
}
if (text.equals("curlright")) {
text = "}";
}
if (text.equals("pipe")) {
text = "|";
}
if (text.equals("backslash")) {
text = "\\";
}
if (text.equals("lt")) {
text = "<";
}
if (text.equals("gt")) {
text = ">";
}
System.out.println(text.charAt(0));
type(text.charAt(0));
}
return "OK";
}
if (event.equals("webup") ) {
robot.mouseWheel(-2);
return "OK";
}
if (event.equals("webdown") ) {
robot.mouseWheel(2);
return "OK";
}
if (event.equals("webback") ) {
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_LEFT);
robot.keyRelease(KeyEvent.VK_LEFT);
robot.keyRelease(KeyEvent.VK_ALT);
...
This file has been truncated, please download it to see its full contents.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
#include <ESP8266HTTPClient.h>
const char *myssid = "kc_0000001";
char httprequest[250];
ESP8266WebServer server(80);
HTTPClient http;
int hostip = 100;
int tries = 0;
const int out1 = 16;
const int out2 = 5;
const int out3 = 4;
const int out4 = 0;
const int out5 = 2;
const int in1 = 14;
const int in2 = 12;
const int in3 = 13;
const int in4 = 3;
const int in5 = 10;
int state1 = 0;
int state2 = 0;
int state3 = 0;
int state4 = 0;
int state5 = 0;
unsigned long timeelapsed = 0;
void handleConfiguration() {
String status = "Configuration : ";
for (int i = 0; i < server.args(); ++i) {
if (server.argName(i) == "ssid") {
String ssid = server.arg(i);
status = status + " ssid = " + ssid;
int address = 11;
for (int j = 0; j < ssid.length(); ++j) {
EEPROM.write(address, ssid.charAt(j));
++address;
}
EEPROM.write(address, 0);
}
if (server.argName(i) == "password") {
String password = server.arg(i);
status = status + " password = " + password;
int address = 51;
for (int j = 0; j < password.length(); ++j) {
EEPROM.write(address, password.charAt(j));
++address;
}
EEPROM.write(address, 0);
}
if (server.argName(i) == "host") {
String host = server.arg(i);
status = status + " host = " + host;
EEPROM.write(101, host.toInt());
}
}
EEPROM.write(0, 1);
EEPROM.commit();
status = status + " rebooting.....";
server.send(200, "text/plain", status);
ESP.restart();
}
void handleRoot() {
String status = "";
if (digitalRead(out1) == HIGH) {
status = "1=ON";
} else {
status = "1=OFF";
}
if (digitalRead(out2) == HIGH) {
status = status + " 2=ON";
} else {
status = status + " 2=OFF";
}
if (digitalRead(out3) == HIGH) {
status = status + " 3=ON";
} else {
status = status + " 3=OFF";
}
if (digitalRead(out4) == HIGH) {
status = status + " 4=ON";
} else {
status = status + " 4=OFF";
}
if (digitalRead(out5) == HIGH) {
status = status + " 5=ON";
} else {
status = status + " 5=OFF";
}
server.send(200, "text/plain", status);
}
void handleCommand() {
String status = "Command: ";
for (int i = 0; i < server.args(); ++i) {
if (server.argName(i) == "out1") {
if (server.arg(i) == "0") {
digitalWrite(out1, LOW);
status = status + " 1=OFF";
state1 = 0;
} else {
digitalWrite(out1, HIGH);
status = status + " 1=ON";
state1 = 1;
}
EEPROM.write(1, state1);
}
if (server.argName(i) == "out2") {
if (server.arg(i) == "0") {
digitalWrite(out2, LOW);
status = status + " 2=OFF";
state2 = 0;
} else {
digitalWrite(out2, HIGH);
status = status + " 2=ON";
state2 = 1;
}
EEPROM.write(2, state2);
}
if (server.argName(i) == "out3") {
if (server.arg(i) == "0") {
digitalWrite(out3, LOW);
status = status + " 3=OFF";
state3 = 0;
} else {
digitalWrite(out3, HIGH);
status = status + " 3=ON";
state3 = 1;
}
EEPROM.write(3, state3);
}
if (server.argName(i) == "out4") {
if (server.arg(i) == "0") {
digitalWrite(out4, LOW);
status = status + " 4=OFF";
state4 = 0;
} else {
digitalWrite(out4, HIGH);
status = status + " 4=ON";
state4 = 1;
}
EEPROM.write(4, state4);
}
if (server.argName(i) == "out5") {
if (server.arg(i) == "0") {
digitalWrite(out5, LOW);
status = status + " 5=OFF";
state5 = 0;
} else {
digitalWrite(out5, HIGH);
status = status + " 5=ON";
state5 = 1;
}
EEPROM.write(5, state5);
}
}
EEPROM.commit();
server.send(200, "text/plain", status);
}
void handleNotFound(){
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void){
pinMode(out1, OUTPUT);
pinMode(out2, OUTPUT);
pinMode(out3, OUTPUT);
pinMode(out4, OUTPUT);
pinMode(out5, OUTPUT);
pinMode(in1, INPUT_PULLUP);
pinMode(in2, INPUT_PULLUP);
pinMode(in3, INPUT_PULLUP);
pinMode(in4, INPUT_PULLUP);
pinMode(in5, INPUT_PULLUP);
digitalWrite(out1, LOW);
digitalWrite(out2, LOW);
digitalWrite(out3, LOW);
digitalWrite(out4, LOW);
digitalWrite(out5, LOW);
delay(1000);
//Serial.begin(9600);
//Serial.println("Jai Omsai");
EEPROM.begin(512);
if (EEPROM.read(1) == 1) {
digitalWrite(out1, HIGH);
state1 = 1;
}
if (EEPROM.read(2) == 1) {
digitalWrite(out2, HIGH);
state2 = 1;
}
if (EEPROM.read(3) == 1) {
digitalWrite(out3, HIGH);
state3 = 1;
}
if (EEPROM.read(4) == 1) {
digitalWrite(out4, HIGH);
state4 = 1;
}
if (EEPROM.read(5) == 1) {
digitalWrite(out5, HIGH);
state5 = 1;
}
char ssid[50];
int address = 11;
int j = 0;
while (EEPROM.read(address) != 0 && address < 50) {
ssid[j] = EEPROM.read(address);
++j;
++address;
}
ssid[j] = 0;
//Serial.print("SSID ");
//Serial.println(ssid);
char password[50];
address = 51;
j = 0;
while (EEPROM.read(address) != 0 && address < 100) {
password[j] = EEPROM.read(address);
++j;
++address;
}
password[j] = 0;
//Serial.print("Password ");
//Serial.println(password);
hostip = EEPROM.read(101);
//Serial.print("Host ");
//Serial.println(hostip);
if (EEPROM.read(0) == 99) {
WiFi.mode(WIFI_AP);
WiFi.softAP(myssid);
EEPROM.write(0, 1);
IPAddress myIP = WiFi.softAPIP();
Serial.println(myIP);
} else {
WiFi.mode(WIFI_STA);
WiFi.setAutoConnect(true);
//Serial.println(myIP);
}
EEPROM.commit();
server.on("/", handleRoot);
server.on("/cmd", handleCommand);
server.on("/conf", handleConfiguration);
server.onNotFound(handleNotFound);
server.begin();
tries = 0;
}
void updateHost() {
if (WiFi.getMode() == WIFI_STA) {
IPAddress myIP = WiFi.localIP();
//Serial.println(myIP);
//Serial.println(WiFi.status());
//Serial.println(WL_CONNECTED);
if (WiFi.status() == WL_CONNECTED) {
sprintf(httprequest, "http://%d.%d.%d.%d:8081/?%s=%d&out1=%d&out2=%d&out3=%d&out4=%d&out5=%d",
myIP[0], myIP[1], myIP[2], hostip, myssid, myIP[3], state1, state2, state3, state4, state5);
http.begin(httprequest); //HTTP
int httpCode = http.GET();
//Serial.println(httpCode);
http.end();
} else {
++tries;
if (tries > 10) {
ESP.restart();
}
}
}
}
void loop(void) {
if (millis() < timeelapsed) {
timeelapsed = millis();
}
if (millis() - timeelapsed > 10000) {
timeelapsed = millis();
updateHost();
}
server.handleClient();
int state = digitalRead(in1);
delay(5);
int checkstate = digitalRead(in1);
if (state == checkstate && state == LOW) {
if (state1 == 0) state1 = 2;
if (state1 == 1) state1 = 3;
}
state = digitalRead(in1);
delay(5);
checkstate = digitalRead(in1);
if (state == checkstate && state == HIGH && state1 > 1) {
if (state1 == 2) {
state1 = 1;
} else {
state1 = 0;
}
digitalWrite(out1, state1);
EEPROM.write(1, state1);
EEPROM.commit();
updateHost();
}
/* 2 */
state = digitalRead(in2);
delay(5);
checkstate = digitalRead(in2);
if (state == checkstate && state == LOW) {
if (state2 == 0) state2 = 2;
if (state2 == 1) state2 = 3;
}
state = digitalRead(in2);
delay(5);
checkstate = digitalRead(in2);
if (state == checkstate && state == HIGH && state2 > 1) {
if (state2 == 2) {
state2 = 1;
} else {
state2 = 0;
}
digitalWrite(out2, state2);
EEPROM.write(2, state2);
EEPROM.commit();
updateHost();
}
/* 3 */
state = digitalRead(in3);
delay(5);
checkstate = digitalRead(in3);
if (state == checkstate && state == LOW) {
if (state3 == 0) state3 = 2;
if (state3 == 1) state3 = 3;
}
state = digitalRead(in3);
delay(5);
checkstate = digitalRead(in3);
if (state == checkstate && state == HIGH && state3 > 1) {
if (state3 == 2) {
state3 = 1;
} else {
state3 = 0;
}
digitalWrite(out3, state3);
EEPROM.write(3, state3);
EEPROM.commit();
updateHost();
}
/* 4 */
state = digitalRead(in4);
delay(5);
checkstate = digitalRead(in4);
if (state == checkstate && state == LOW) {
if (state4 == 0) state4 = 2;
if (state4 == 1) state4 = 3;
}
state = digitalRead(in4);
delay(5);
checkstate = digitalRead(in4);
if (state == checkstate && state == HIGH && state4 > 1) {
if (state4 == 2) {
state4 = 1;
} else {
state4 = 0;
}
digitalWrite(out4, state4);
EEPROM.write(4, state4);
EEPROM.commit();
updateHost();
}
/* 5 */
state = digitalRead(in5);
delay(5);
checkstate = digitalRead(in5);
if (state == checkstate && state == LOW) {
if (state5 == 0) state5 = 2;
if (state5 == 1) state5 = 3;
}
state = digitalRead(in5);
delay(5);
checkstate = digitalRead(in5);
if (state == checkstate && state == HIGH && state5 > 1) {
if (state5 == 2) {
state5 = 1;
} else {
state5 = 0;
}
digitalWrite(out5, state5);
EEPROM.write(5, state5);
EEPROM.commit();
updateHost();
}
if (state1 == 2 && state5 == 2) {
EEPROM.write(0, 99);
EEPROM.commit();
digitalWrite(out1, 0);
digitalWrite(out2, 0);
digitalWrite(out3, 0);
digitalWrite(out4, 0);
digitalWrite(out5, 0);
delay(10000);
ESP.restart();
}
}
#include <OneWire.h>
#include <DallasTemperature.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <SparkFun_APDS9960.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
#include <ESP8266HTTPClient.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 1
// If using software SPI (the default case):
#define OLED_MOSI 2
#define OLED_CLK 14
#define OLED_DC 16
#define OLED_CS 12
#define OLED_RESET 0
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);
SparkFun_APDS9960 apds = SparkFun_APDS9960();
#define ONE_WIRE_BUS D10
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
const char *myssid = "kc_0000003";
//const char *myssid = "kc_0000002";
char httprequest[250];
ESP8266WebServer server(80);
HTTPClient http;
int hostip = 100;
int tries = 0;
unsigned long timeelapsed = 0;
unsigned int setTemp = 24;
unsigned int curTemp = 24;
unsigned int ac = 0;
void handleRoot() {
String status = "OK";
server.send(200, "text/plain", status);
}
void handleCommand() {
String status = "Command: ";
for (int i = 0; i < server.args(); ++i) {
if (server.argName(i) == "display") {
displayOnScreen(server.arg(i));
status += server.argName(i);
}
if (server.argName(i) == "setpoint") {
setTemp = server.arg(i).toInt();
displaySetPoint();
}
if (server.argName(i) == "ac") {
if (server.arg(i) == "0" || server.arg(i) == "OFF") {
ac = 0;
} else {
ac = 1;
}
displayTemperature();
}
status = status + " " + server.argName(i) + " " + server.arg(i);
}
server.send(200, "text/plain", status);
}
void handleNotFound(){
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void){
// by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
display.begin(SSD1306_SWITCHCAPVCC);
display.display();
delay(2000);
if ( !apds.init() ) {
displayOnScreen("I-ERR");
}
// Adjust the Proximity sensor gain
if ( !apds.setGestureGain(GGAIN_1X) ) {
displayOnScreen("G-ERR");;
}
// Start running the APDS-9960 gesture sensor engine
if ( apds.enableGestureSensor(true) ) {
displayOnScreen("READY");
} else {
displayOnScreen("E-ERR");
}
EEPROM.begin(512);
WiFi.mode(WIFI_STA);
WiFi.begin("XXXXXX");
WiFi.setAutoConnect(true);
EEPROM.commit();
server.on("/", handleRoot);
server.on("/cmd", handleCommand);
server.onNotFound(handleNotFound);
server.begin();
tries = 0;
sensors.begin();
}
void updateHost() {
if (WiFi.getMode() == WIFI_STA) {
IPAddress myIP = WiFi.localIP();
//Serial.println(myIP);
//Serial.println(WiFi.status());
//Serial.println(WL_CONNECTED);
if (WiFi.status() == WL_CONNECTED) {
sprintf(httprequest, "http://%d.%d.%d.%d:8081/?%s=%d.%d.%d.%d&set=%d&temp=%d&ac=%d",
190, 180, 161, 67, myssid, myIP[0], myIP[1], myIP[2], myIP[3], setTemp, curTemp, ac);
http.begin(httprequest); //HTTP
int httpCode = http.GET();
//Serial.println(httpCode);
http.end();
} else {
++tries;
if (tries > 10) {
ESP.restart();
}
}
}
}
void loop(void) {
if (millis() < timeelapsed) {
timeelapsed = millis();
}
if (millis() - timeelapsed > 10000) {
timeelapsed = millis();
displayTemperature();
updateHost();
}
handleGesture();
server.handleClient();
}
void handleGesture() {
if ( apds.isGestureAvailable() ) {
switch ( apds.readGesture() ) {
case DIR_UP:
setTemp++;
displaySetPoint();
break;
case DIR_DOWN:
setTemp--;
displaySetPoint();
break;
case DIR_LEFT:
ac = 0;
displayTemperature();
break;
case DIR_RIGHT:
ac = 1;
displayTemperature();
break;
case DIR_NEAR:
break;
case DIR_FAR:
break;
default:
break;
}
timeelapsed = millis();
updateHost();
}
}
void displayTemperature() {
char charVal[10];
float temp = 0.0;
sensors.requestTemperatures();
temp = sensors.getTempCByIndex(0);
delay(100);
curTemp = int(temp);
sprintf(charVal, "%d", curTemp);
String tempStr = String(charVal);
tempStr.trim();
displayOnScreen(tempStr + " Deg");
}
void displaySetPoint() {
char charVal[10];
sprintf(charVal, "%d", setTemp);
String tempStr = String(charVal);
tempStr.trim();
displayOnScreen("Set " + tempStr + " Deg");
}
void displayOnScreen(String what) {
String manualDisplay = "AC Auto";
if (ac == 0) {
manualDisplay = "AC Off";
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("Hackster.io Project\n\r" + manualDisplay);
display.setTextSize(2);
display.println(what);
display.display();
}
Lambda Node.js Code
JavaScriptvar https = require('https');
exports.handler = function (request, context) {
log("DEGUG:", "Request ", JSON.stringify(request));
log("DEGUG:", "Context ", JSON.stringify(context));
if (request.directive.header.namespace === 'Alexa.Discovery' && request.directive.header.name === 'Discover') {
handleDiscovery(request, context, "");
}
else if (request.directive.header.namespace === 'Alexa.PowerController') {
if (request.directive.header.name === 'TurnOn' || request.directive.header.name === 'TurnOff') {
handlePowerControl(request, context);
}
}
else if (request.directive.header.namespace === 'Alexa.LockController') {
if (request.directive.header.name === 'Lock' || request.directive.header.name === 'Unlock') {
handleLockControl(request, context);
}
}
else if (request.directive.header.namespace === 'Alexa.Speaker') {
if (request.directive.header.name === 'SetMute') {
handleVolumeControl(request, context);
}
}
else if (request.directive.header.namespace === 'Alexa.InputController') {
if (request.directive.header.name === 'SelectInput') {
handleInputControl(request, context);
}
}
else if (request.directive.header.namespace === 'Alexa.ChannelController') {
if (request.directive.header.name === 'ChangeChannel') {
handleChannelControl(request, context);
}
}
else if (request.directive.header.namespace === 'Alexa.ThermostatController') {
if (request.directive.header.name === 'SetTargetTemperature') {
handleThermostatControl(request, context);
}
}
function handleDiscovery(request, context) {
var requestToken = request.directive.payload.scope.token;
getJsonRequest("getdevices=" + requestToken, function(data) {
var payload = data;
var header = request.directive.header;
header.name = "Discover.Response";
log("DEBUG", "Discovery Response: ", JSON.stringify({ header: header, payload: payload }));
context.succeed({ event: { header: header, payload: payload } });
});
}
function log(message, message1, message2) {
console.log(message + message1 + message2);
}
function handlePowerControl(request, context) {
var requestMethod = request.directive.header.name;
// get user token pass in request
var requestToken = request.directive.endpoint.scope.token;
var endpointId = request.directive.endpoint.endpointId;
var powerResult = "NONE";
if (requestMethod === "TurnOn") {
// Make the call to your device cloud for control
// powerResult = stubControlFunctionToYourCloud(endpointId, token, request);
powerResult = "ON";
}
else if (requestMethod === "TurnOff") {
// Make the call to your device cloud for control and check for success
// powerResult = stubControlFunctionToYourCloud(endpointId, token, request);
powerResult = "OFF";
}
var contextResult = {
"properties": [{
"namespace": "Alexa.PowerController",
"name": "powerState",
"value": powerResult,
"timeOfSample": getUTCTimeStamp(), //retrieve from result.
"uncertaintyInMilliseconds": 500
}]
};
var responseHeader = request.directive.header;
responseHeader.namespace = "Alexa";
responseHeader.name = "Response";
//responseHeader.messageId = responseHeader.messageId + "-R";
var responseEndpoint = request.directive.endpoint;
var response = {
context: contextResult,
event: {
header: responseHeader
},
endpoint : responseEndpoint,
payload: {}
};
getJsonRequest("access_token=" + requestToken + "&endpointId=" + endpointId + "&state=" + powerResult, function(data) {
context.succeed(response);
});
log("DEBUG", "Alexa.PowerController ", JSON.stringify(response));
}
function handleLockControl(request, context) {
var requestMethod = request.directive.header.name;
// get user token pass in request
var requestToken = request.directive.endpoint.scope.token;
var endpointId = request.directive.endpoint.endpointId;
var lockResult = "JAMMED";
if (requestMethod === "Lock") {
// Make the call to your device cloud for control
// powerResult = stubControlFunctionToYourCloud(endpointId, token, request);
lockResult = "LOCKED";
}
else if (requestMethod === "Unlock") {
// Make the call to your device cloud for control and check for success
// powerResult = stubControlFunctionToYourCloud(endpointId, token, request);
lockResult = "UNLOCKED";
}
var contextResult = {
"properties": [{
"namespace": "Alexa.LockController",
"name": "lockState",
"value": lockResult,
"timeOfSample": getUTCTimeStamp(), //retrieve from result.
"uncertaintyInMilliseconds": 500
}]
};
var responseHeader = request.directive.header;
responseHeader.namespace = "Alexa";
responseHeader.name = "Response";
//responseHeader.messageId = responseHeader.messageId + "-R";
var responseEndpoint = request.directive.endpoint;
var response = {
context: contextResult,
event: {
header: responseHeader
},
endpoint : responseEndpoint,
payload: {}
};
var stateResult = "ON";
if (lockResult == "UNLOCKED") {
stateResult = "OFF";
}
getJsonRequest("access_token=" + requestToken + "&endpointId=" + endpointId + "&state=" + stateResult, function(data) {
context.succeed(response);
});
log("DEBUG", "Alexa.LockController ", JSON.stringify(response));
}
function handleVolumeControl(request, context) {
var requestMethod = request.directive.header.name;
// get user token pass in request
var requestToken = request.directive.endpoint.scope.token;
var endpointId = request.directive.endpoint.endpointId;
var muteResult = request.directive.payload.mute;
var contextResult = {
"properties": [{
"namespace": "Alexa.Speaker",
"name": "muted",
"value": muteResult,
"timeOfSample": getUTCTimeStamp(), //retrieve from result.
"uncertaintyInMilliseconds": 500
}]
};
var responseHeader = request.directive.header;
responseHeader.namespace = "Alexa";
responseHeader.name = "Response";
//responseHeader.messageId = responseHeader.messageId + "-R";
var responseEndpoint = request.directive.endpoint;
var response = {
context: contextResult,
event: {
header: responseHeader
},
endpoint : responseEndpoint,
payload: {}
};
getJsonRequest("access_token=" + requestToken + "&endpointId=" + endpointId + "&state=tvmute", function(data) {
context.succeed(response);
});
log("DEBUG", "Alexa.Speaker ", JSON.stringify(response));
}
function handleInputControl(request, context) {
var requestMethod = request.directive.header.name;
// get user token pass in request
var requestToken = request.directive.endpoint.scope.token;
var endpointId = request.directive.endpoint.endpointId;
var inputResult = request.directive.payload.input;
var contextResult = {
"properties": [{
"namespace": "Alexa.InputController",
"name": "input",
"value": inputResult,
"timeOfSample": getUTCTimeStamp(), //retrieve from result.
"uncertaintyInMilliseconds": 500
}]
};
var responseHeader = request.directive.header;
responseHeader.namespace = "Alexa";
responseHeader.name = "Response";
//responseHeader.messageId = responseHeader.messageId + "-R";
var responseEndpoint = request.directive.endpoint;
var response = {
context: contextResult,
event: {
header: responseHeader
},
endpoint : responseEndpoint,
payload: {}
};
var stateResult = "tvprevious";
if (inputResult == "AV" || inputResult == "SET TOP BOX" || inputResult == "AV" || inputResult == "CABLE") {
stateResult = "tvnext";
}
getJsonRequest("access_token=" + requestToken + "&endpointId=" + endpointId + "&state=" + stateResult, function(data) {
context.succeed(response);
});
log("DEBUG", "Alexa.InputController ", JSON.stringify(response));
}
function handleChannelControl(request, context) {
var requestMethod = request.directive.header.name;
// get user token pass in request
var requestToken = request.directive.endpoint.scope.token;
var endpointId = request.directive.endpoint.endpointId;
var channelResult = request.directive.payload.channel;
var contextResult = {
"properties": [{
"namespace": "Alexa.ChannelController",
"name": "channel",
"value": channelResult,
"timeOfSample": getUTCTimeStamp(), //retrieve from result.
"uncertaintyInMilliseconds": 500
}]
};
var responseHeader = request.directive.header;
responseHeader.namespace = "Alexa";
responseHeader.name = "Response";
//responseHeader.messageId = responseHeader.messageId + "-R";
var responseEndpoint = request.directive.endpoint;
var response = {
context: contextResult,
event: {
header: responseHeader
},
endpoint : responseEndpoint,
payload: {}
};
var channel = "";
if (request.directive.payload.channelMetadata.name == undefined) {
channel = request.directive.payload.channel.number;
} else {
channel = request.directive.payload.channelMetadata.name;
}
getJsonRequest("access_token=" + requestToken + "&endpointId=" + endpointId + "&state=tvchannel_" + channel, function(data) {
context.succeed(response);
});
log("DEBUG", "Alexa.ChannelController ", JSON.stringify(response));
}
function handleThermostatControl(request, context) {
var requestMethod = request.directive.header.name;
// get user token pass in request
var requestToken = request.directive.endpoint.scope.token;
var endpointId = request.directive.endpoint.endpointId;
var thermostatResult = request.directive.payload.targetSetpoint;
var contextResult = {
"properties": [{
"namespace": "Alexa.ThermostatController",
"name": "targetSetpoint",
"value": thermostatResult,
"timeOfSample": getUTCTimeStamp(), //retrieve from result.
"uncertaintyInMilliseconds": 500
}]
};
var responseHeader = request.directive.header;
responseHeader.namespace = "Alexa";
responseHeader.name = "Response";
//responseHeader.messageId = responseHeader.messageId + "-R";
var responseEndpoint = request.directive.endpoint;
var response = {
context: contextResult,
event: {
header: responseHeader
},
endpoint : responseEndpoint,
payload: {}
};
getJsonRequest("access_token=" + requestToken + "&endpointId=" + endpointId + "&state=setpoint_" + thermostatResult.value, function(data) {
context.succeed(response);
});
log("DEBUG", "Alexa.ThermostatController ", JSON.stringify(response));
}
function getUTCTimeStamp(){
var datetime = new Date().toISOString();
log("DEBUG", "UTC Date Time ", datetime);
return datetime;
}
};
var getJsonRequest = function(query, callback){
https.get("yourservercgiscript?" + query, function(res) {
var body = '';
res.on('data', function(data){
body += data;
});
res.on('end', function(){
console.log("DEBUG", "Body ", body);
var result = JSON.parse(body);
callback(result);
});
}).on('error', function(e){
console.log('Error: ' + e);
});
};
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class JSONServer {
final openingPage page;
JSONServer(final openingPage page) {
this.page = page;
try {
InetSocketAddress addr = new InetSocketAddress(8081);
HttpServer server = HttpServer.create(addr, 0);
server.createContext("/", new JSONHandler());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("Server is listening on port 8081");
} catch (Exception e) {
e.printStackTrace();
}
}
private class JSONHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
call(exchange);
}
private synchronized void call(HttpExchange exchange) {
new Thread(new JSONRunnable(exchange)).start();
}
}
private class JSONRunnable implements Runnable {
protected HttpExchange exchange = null;
public JSONRunnable(HttpExchange exchange) {
this.exchange = exchange;
}
@Override
public void run() {
try {
Headers responseHeaders = exchange.getResponseHeaders();
OutputStream responseBody = exchange.getResponseBody();
String uri = exchange.getRequestURI().toString();
if (exchange.getRequestMethod().equals("POST")) {
Headers requestHeaders = exchange.getRequestHeaders();
System.out.println(requestHeaders.getFirst("Content-Type"));
String boundary = requestHeaders.getFirst("Content-Type").replaceAll("multipart/form-data; boundary=", "");
System.out.println(boundary);
InputStream is = exchange.getRequestBody();
byte[] data = getInputAsBinary(is);
is.close();
String stringData = new String(data);
int start = stringData.indexOf(boundary);
start = stringData.indexOf('\r', start+1);
start = stringData.indexOf('\r', start+1);
start = stringData.indexOf('\r', start+1);
start = stringData.indexOf('\r', start+1)+2;
int end = stringData.indexOf(boundary, start);
for (int i = end; i < data.length; ++i) {
byte[] compare = Arrays.copyOfRange(data, end, end + boundary.length());
System.out.println(new String(compare));
if (Arrays.equals(compare, boundary.getBytes())) {
break;
}
++end;
}
end -= 4;
System.out.println(end-start);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(data, start, end-start);
FileOutputStream fos = new FileOutputStream("hycan.png");
fos.write(bos.toByteArray());
fos.close();
//System.out.print(stringData.substring(start, end));
exchange.sendResponseHeaders(200, 0);
responseHeaders.set("Content-Type", "text/html");
responseBody.write("OK".getBytes());
responseBody.close();
return;
}
if (uri.indexOf("?") < 0) {
String resource = uri.replaceAll("/", "");
if (resource.equals("")) resource = "index.html";
if (resource.equals("conf")) resource = "conf.html";
exchange.sendResponseHeaders(200, 0);
try {
InputStream in = JSONServer.class.getResourceAsStream("/resources/" + resource);
if (in == null) {
responseHeaders.set("Content-Type", "text/html");
responseBody.write(resource.getBytes());
responseBody.close();
return;
}
ByteArrayOutputStream fileBytes=new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int nread = 0;
while ((nread = in.read(buffer)) != -1) {
fileBytes.write(buffer, 0, nread);
}
if (resource.endsWith(".htm") || resource.endsWith(".html")) {
responseHeaders.set("Content-Type", "text/html");
} else if (resource.endsWith(".js") ) {
responseHeaders.set("Content-Type", "text/javascript");
} else if (resource.endsWith(".css") ) {
responseHeaders.set("Content-Type", "text/css");
} else if (resource.endsWith(".ico") ) {
responseHeaders.set("Content-Type", "image/ico");
} else if (resource.endsWith(".png") ) {
responseHeaders.set("Content-Type", "image/png");
} else if (resource.endsWith(".jpg") ) {
responseHeaders.set("Content-Type", "image/jpg");
} else if (resource.endsWith(".jpeg") ) {
responseHeaders.set("Content-Type", "image/jpg");
} else {
responseHeaders.set("Content-Type", "text/plain");
}
responseBody.write(fileBytes.toByteArray());
fileBytes.close();
in.close();
responseBody.close();
} catch (Exception e) {
responseHeaders.set("Content-Type", "text/html");
responseBody.write(resource.getBytes());
responseBody.close();
e.printStackTrace();
}
return;
}
String query = exchange.getRequestURI().getQuery();
if (query == null) {
exchange.sendResponseHeaders(200, 0);
responseHeaders.set("Content-Type", "text/html");
responseBody.write("OK".getBytes());
responseBody.close();
return;
}
System.out.println(query);
String app = processCommand(query);
int i = query.indexOf("callback=");
if (i >= 0) {
i +=9;
int j = query.indexOf("&", i);
String callback = "";
if (j > i) callback = query.substring(i, j);
exchange.sendResponseHeaders(200, 0);
responseHeaders.set("Content-Type", "text/json");
responseBody.write((callback + "({\"result\" : \"" + app + "\"});").getBytes());
responseBody.close();
} else {
exchange.sendResponseHeaders(200, 0);
responseHeaders.set("Content-Type", "text/html");
responseBody.write("OK".getBytes());
responseBody.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String processCommand(String query) {
String result = "OK";
try {
int i = query.indexOf("cmd=");
if (i >= 0) {
if (query.indexOf("&") > i) {
result = page.pageEvent(query.substring(i+4, query.indexOf("&")));
} else {
result = page.pageEvent(query.substring(i+4));
}
}
if (query.startsWith("kc_")) {
query = query.replaceAll("&", "*");
query = query.replaceAll("=", ":");
System.out.println(query);
result = page.pageEvent(query);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
public static byte[] getInputAsBinary(InputStream requestStream) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
byte[] buf = new byte[100000];
int bytesRead=0;
while ((bytesRead = requestStream.read(buf)) != -1){
bos.write(buf, 0, bytesRead);
}
requestStream.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return bos.toByteArray();
}
}
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<link rel="apple-touch-icon" href="ok.png"/>
<script src="jquery-min.js"></script>
<script src="jquery-ui.js"></script>
<link rel="stylesheet" href="index.css">
<script src="index.js"></script>
<script src="uitouch.js"></script>
</head>
<body center>
<div class="block">
<div class="heading">TV</div>
<div>
<label id="tvpower" class="clickable button">Power</label>
<label id="tvsource" class="clickable button">Source</label>
</div>
<div class="center" style="margin-top:25px">
<label id="tvvolumedown" class="clickable button" style="margin-left:15px">Vol-</label>
<label id="tvmute" class="clickable button">Mute</label>
<label id="tvvolumeup" class="clickable button" style="margin-right:15px">Vol+</label>
</div>
</div>
<div class="block">
<div class="heading">Set-Top Box</div>
<div>
<label id="remotepower" class="clickable button">Power</label>
<label id="remotemute" class="clickable button">Mute</label>
</div>
<div class="center" style="margin-top:20px">
<div>
<label id="remoteguide" class="clickable button">Guide</label>
</div>
<div>
<label id="remotevolumeup" class="clickable button">Vol+</label>
<label id="remoteup" class="clickable button">Up</label>
<label id="remotechannelup" class="clickable button">CH+</label>
</div>
<div>
<label id="remoteup" class="clickable button" >Left</label>
<label id="remoteok" class="clickable button">Select</label>
<label id="remotedown" class="clickable button">Right</label>
</div>
<div>
<label id="remotevolumedown" class="clickable button">Vol-</label>
<label id="remotedown" class="clickable button">Down</label>
<label id="remotechanneldown" class="clickable button">CH-</label>
</div>
<div>
<label id="remoteback" class="clickable button">Back</label>
</div>
<div>
<label id="remote1" class="clickable button">1</label>
<label id="remote2" class="clickable button">2</label>
<label id="remote3" class="clickable button">3</label>
<label id="remote4" class="clickable button">4</label>
<label id="remote5" class="clickable button">5</label>
</div>
<div>
<label id="remote6" class="clickable button">6</label>
<label id="remote7" class="clickable button">7</label>
<label id="remote8" class="clickable button">8</label>
<label id="remote9" class="clickable button">9</label>
<label id="remote0" class="clickable button">0</label>
</div>
</div>
</div>
<div class="block">
<div class="heading">Web</div>
<div class="center" style="margin-top:20px">
<div>
<img class="images button clickable" id="google"/>
<img class="images button clickable" id="youtube"/>
<img class="images button clickable" id="tunein"/>
</div>
<div>
<img class="images button clickable" id="netflix"/>
<img class="images button clickable" id="amazonprime"/>
<img class="images button clickable" id="whatsapp"/>
</div>
<div>
<label id="webup" class="clickable button">Up</label>
</div>
<div>
<label id="webback" class="clickable button">Back</label>
<label id="close" class="clickable button">Close</label>
<label id="webforward" class="clickable button">Forward</label>
</div>
<div>
<label id="webdown" class="clickable button">Down</label>
</div>
</div>
</div>
<div class="block">
<div class="heading">Mouse</div>
<div class="center" style="margin-top:20px">
<div id="draggable" class="ui-widget-content center">
<img class="images button clickable" id="mouse"/>
</div>
<div class="center">
<label id="webleftclick" class="clickable button">Select</label>
<img class="images button clickable" id="invisible"/>
<label id="webrightclick" class="clickable button">R Click</label>
</div>
</div>
</div>
<div class="block">
<div class="heading">Keyboard</div>
<div class="center" style="margin-top:20px">
<div class="keypad">
<label class="clickable key alpha">q</label>
<label class="clickable key alpha">w</label>
<label class="clickable key alpha">e</label>
<label class="clickable key alpha">r</label>
<label class="clickable key alpha">t</label>
<label class="clickable key alpha">y</label>
<label class="clickable key alpha">u</label>
<label class="clickable key alpha">i</label>
<label class="clickable key alpha">o</label>
<label class="clickable key alpha">p</label>
</div>
<div class="keypad">
<label class="clickable key alpha">a</label>
<label class="clickable key alpha">s</label>
<label class="clickable key alpha">d</label>
<label class="clickable key alpha">f</label>
<label class="clickable key alpha">g</label>
<label class="clickable key alpha">h</label>
<label class="clickable key alpha">j</label>
<label class="clickable key alpha">k</label>
<label class="clickable key alpha">l</label>
</div>
<div class="keypad">
<label id="keycap" class="clickable key">cap</label>
<label class="clickable key alpha">z</label>
<label class="clickable key alpha">x</label>
<label class="clickable key alpha">c</label>
<label class="clickable key alpha">v</label>
<label class="clickable key alpha">b</label>
<label class="clickable key alpha">n</label>
<label class="clickable key alpha">m</label>
<label id="keydel" class="clickable key">del</label>
</div>
<div class="keypad">
<label class="clickable key">@</label>
<label id="keyspace" class="clickable key">space</label>
<label id="keyenter" class="clickable key">enter</label>
<label class="clickable key">.</label>
</div>
<div class="keypad">
<label class="clickable key">1</label>
<label class="clickable key">2</label>
<label class="clickable key">3</label>
<label class="clickable key">4</label>
<label class="clickable key">5</label>
<label class="clickable key">6</label>
<label class="clickable key">7</label>
<label class="clickable key">8</label>
<label class="clickable key">9</label>
<label class="clickable key">0</label>
</div>
<div class="keypad">
<label class="clickable key">~</label>
<label class="clickable key">/</label>
<label class="clickable key">!</label>
<label class="clickable key">#</label>
<label class="clickable key">$</label>
<label class="clickable key">%</label>
<label class="clickable key">^</label>
<label class="clickable key">&</label>
<label class="clickable key">*</label>
</div>
<div class="keypad">
<label class="clickable key">(</label>
<label class="clickable key">)</label>
<label class="clickable key">_</label>
<label class="clickable key">+</label>
<label class="clickable key">-</label>
<label class="clickable key">=</label>
<label class="clickable key">{</label>
<label class="clickable key">}</label>
<label class="clickable key">[</label>
<label class="clickable key">]</label>
</div>
<div class="keypad">
<label class="clickable key">|</label>
<label class="clickable key">\</label>
<label class="clickable key">:</label>
<label class="clickable key">"</label>
<label class="clickable key">;</label>
<label class="clickable key">'</label>
<label class="clickable key"><</label>
<label class="clickable key">></label>
<label class="clickable key">?</label>
</div>
</div>
</div>
</body>
</html>
/* A bit custom styling */
body {
background-color: black;
color: white;
margin-top: 50px;
}
.block {
border-radius: 25px;
border: 2px solid #73AD21;
padding: 10px;
margin-bottom: 25px;
}
#tvvolumeup, #tvvolumedown
{
background: #fff2cc;
background: -webkit-linear-gradient(#fff2cc, #ffd966);
background: linear-gradient(#fff2cc, #ffd966);
border: 1px solid #7f6000;
border-radius: 1000px;
width: 72px;
height: 72px;
color: #000000;
display: inline-block;
font: normal 400 15px/72px "Calibri", sans-serif;
text-align: center;
text-shadow: none;
}
#remoteup, #remotedown, #remotechannelup, #remotechanneldown,
#remotevolumeup, #remotevolumedown, #webup, #webdown, #webback, #webforward
{
background: #fff2cc;
background: -webkit-linear-gradient(#fff2cc, #ffd966);
background: linear-gradient(#fff2cc, #ffd966);
border: 1px solid #7f6000;
border-radius: 1000px;
width: 72px;
height: 72px;
color: #000000;
display: inline-block;
font: normal 400 15px/72px "Calibri", sans-serif;
text-align: center;
text-shadow: none;
}
#remote1, #remote2, #remote3, #remote4,
#remote5, #remote6, #remote7, #remote8, #remote9, #remote0
{
background: #fff2cc;
background: -webkit-linear-gradient(#fff2cc, #ffd966);
background: linear-gradient(#fff2cc, #ffd966);
border: 1px solid #7f6000;
border-radius: 500px;
width: 54px;
height: 54px;
color: #000000;
display: inline-block;
font: normal 400 15px/54px "Calibri", sans-serif;
text-align: center;
text-shadow: none;
}
#remotevolumeup, #remotevolumedown {
float: left;
background: #11ff11;
background: -webkit-linear-gradient(#11cc11, #11ff11 50%, #11cc11);
background: linear-gradient(#11cc11, #11ff11 50%, #11cc11);
}
#remotechannelup, #remotechanneldown {
float: right;
background: #11ff11;
background: -webkit-linear-gradient(#11cc11, #11ff11 50%, #11cc11);
background: linear-gradient(#11cc11, #11ff11 50%, #11cc11);
}
#remoteback, #tvmute, #select, #remoteok, #remoteguide,
#close, #webrightclick, #webleftclick {
background: #ffffff;
background: -webkit-linear-gradient(#cccccc, #ffffff 50%, #cccccc);
background: linear-gradient(#cccccc, #ffffff 50%, #cccccc);
border: 1px solid #7f6000;
border-radius: 1000px;
width: 110px;
height: 49px;
color: #000000;
display: inline-block;
font: normal 400 15px/49px "Calibri", sans-serif;
text-align: center;
text-shadow: none;
margin: 1px;
}
#remoteback, #remoteguide {
margin-top: 10px;
margin-bottom: 10px;
}
#tvpower, #remotepower, #tvsource, #remotemute {
background: #f4cccc;
background: -webkit-linear-gradient(#e06666, #f4cccc 50%, #e06666);
background: linear-gradient(#e06666, #f4cccc 50%, #e06666);
border: 1px solid #7f6000;
border-radius: 1000px;
width: 125px;
height: 49px;
color: #000000;
display: inline-block;
font: normal 400 15px/49px "Calibri", sans-serif;
text-align: center;
word-break: break-all
text-shadow: none;
margin: 5px;
}
#tvsource, #remotemute {
background: #ffffff;
background: -webkit-linear-gradient(#cccccc, #ffffff 50%, #cccccc);
background: linear-gradient(#cccccc, #ffffff 50%, #cccccc);
float: right;
}
img {
padding: 5px;
width: 64px;
height: 64px;
}
input {
border: 2px solid #dadada;
border-radius: 7px;
width: 220px;
height: 40px;
font-size: 18px;
}
.input:focus {
outline: none;
border-color: #9ecaed;
box-shadow: 0 0 10px #9ecaed;
}
.header {
margin: auto;
text-align: center;
position: fixed;
top: 0;
color: white;
width:100%;
font-family: Geneva, Tahoma, Verdana, sans-serif;
font-size: 12px;
font-style: normal;
font-variant: normal;
font-weight: 400;
}
.heading {
margin: 15px;
text-align: left;
color: white;
font-family: Geneva, Tahoma, Verdana, sans-serif;
font-size: 24px;
font-style: normal;
font-variant: normal;
font-weight: 400;
}
#head {
font-size: 14px;
}
.center {
margin: margin: 0 auto;
text-align: center;
}
.clickable {
cursor: pointer;
}
.withpadding {
padding: 10px;
}
.keypad {
margin: margin: 0 auto;
text-align: justify;
font-size: 0.1px; /* IE 9 & 10 don't like font-size: 0; */
/*border: 2px solid white;*/
display: inline-block;
}
.keypad label {
background: #999999;
background: -webkit-linear-gradient(#666666, #999999 50%, #666666);
background: linear-gradient(#666666, #999999 50%, #666666);
border-radius: 3px;
width: 15px;
heigth: 50px;
padding: 10px 5px;
color: #ffffff;
display: inline-block;
font: normal 400 24px/1 "Calibri", sans-serif;
text-align: center;
text-shadow: none;
margin : 4px;
}
.keypad:after {
content: '';
width: 100%; /* Ensures there are at least 2 lines of text, so justification works */
display: inline-block;
}
#keydel, #keycap {
font: normal 400 20px/1 "Calibri", sans-serif;
width: 32px;
heigth: 50px;
background: #ffffff;
background: -webkit-linear-gradient(#cccccc, #ffffff 50%, #cccccc);
background: linear-gradient(#cccccc, #ffffff 50%, #cccccc);
color: #000000;
}
#keyspace {
width: 96px;
heigth: 50px;
background: #ffffff;
background: -webkit-linear-gradient(#cccccc, #ffffff 50%, #cccccc);
background: linear-gradient(#cccccc, #ffffff 50%, #cccccc);
color: #000000;
}
#keyenter {
width: 76px;
heigth: 50px;
background: #ffffff;
background: -webkit-linear-gradient(#cccccc, #ffffff 50%, #cccccc);
background: linear-gradient(#cccccc, #ffffff 50%, #cccccc);
color: #000000;
}
#keyat {
width: 36px;
heigth: 50px;
}
.switch {
background: #ffffff;
background: -webkit-linear-gradient(#cccccc, #ffffff 50%, #cccccc);
background: linear-gradient(#cccccc, #ffffff 50%, #cccccc);
border: 1px solid #7f6000;
border-radius: 1000px;
width: 100px;
height: 49px;
color: #000000;
display: inline-block;
font: normal 400 15px/49px "Calibri", sans-serif;
text-align: center;
text-shadow: none;
margin: 1px;
}
var urlHome = "";
var imagesLoaded = 0;
var images = ["google", "youtube", "tunein", , "netflix", "amazonprime", "whatsapp",
"invisible", "mouse"];
$(document).ready(function() {
urlHome = window.location.href;
if (urlHome.lastIndexOf("/") > 6) {
urlHome = urlHome.substring(0, urlHome.lastIndexOf("/"));
}
loadImages();
handleSizes()
$( "#draggable" ).draggable();
mousePosition()
getSwitchBoards();
});
function loadImages() {
$("#" + images[imagesLoaded]).attr("src", images[imagesLoaded] + ".png");
imagesLoaded++;
if (imagesLoaded < images.length) {
setTimeout(loadImages, 300);
}
}
$( window ).resize(function() {
handleSizes();
});
function handleSizes() {
var css = "";
css = "" + ($(window).innerWidth() * 0.009) + "px";
$(".keypad label").css("margin", css)
}
function getSwitchBoards() {
url = urlHome + "/?cmd=getSwitchBoards";
$.ajax({
url: url,
dataType: "jsonp",
crossDomain : true,
success: function (data) {
app = JSON.stringify(data);
console.log(app);
if (data.result.length > 0) {
var switchBoards = data.result.split("|");
for (var i = 0; i < switchBoards.length; ++i) {
var switchBoard = switchBoards[i];
var html = "<div class='block'>\n";
html += "<div class='center' style='margin-top:20px'>";
html += "<div class='heading'>" + switchBoard.split(",")[1] + "</div>";
html += "<div>";
html += "<label id='" + switchBoard.split(",")[0] + ":out1' class='switch clickable button'>" + switchBoard.split(",")[2].split(":")[0] + "</label>";
html += "</div>";
html += "<div>";
html += "<label id='" + switchBoard.split(",")[0] + ":out2' class='switch clickable button'>" + switchBoard.split(",")[3].split(":")[0] + "</label>";
html += "<label id='" + switchBoard.split(",")[0] + ":out3' class='switch clickable button'>" + switchBoard.split(",")[4].split(":")[0] + "</label>";
html += "<label id='" + switchBoard.split(",")[0] + ":out4' class='switch clickable button'>" + switchBoard.split(",")[5].split(":")[0] + "</label>";
html += "</div>";
html += "<div>";
html += "<label id='" + switchBoard.split(",")[0] + ":out5' class='switch clickable button'>" + switchBoard.split(",")[6].split(":")[0] + "</label>";
html += "</div>";
html += "</div>";
html += "</div>";
$("body").append(html);
}
}
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log(textStatus);
},
timeout: 5000
});
}
$(document).on("click", ".button", function(event){
url = urlHome + "/?cmd=" + event.target.id;
$.ajax({
url: url,
dataType: "jsonp",
crossDomain : true,
success: function (data) {
app = JSON.stringify(data);
console.log(JSON.stringify(app));
/*
if (event.target.id === "showtatasky") {
window.location = urlHome + "/tatasky.html";
}
if (event.target.id === "showtv") {
window.location = urlHome;
}
if (app === '{"result":"web"}') {
window.location = urlHome + "/web.html";
}
*/
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log(textStatus);
},
timeout: 5000
});
});
$(document).on("click", ".key", function(event){
var target = event.target || event.srcElement;
var key = target.innerHTML;
console.log(key);
if (target.id == "keycap") {
var alphas = document.getElementsByClassName("alpha");
lowerCase = 1;
if (alphas.item(0).innerHTML == "q") {
lowerCase = 0;
}
for (var i = 0; i < alphas.length; i++) {
var str = alphas.item(i).innerHTML;
if (lowerCase == 0) {
alphas.item(i).innerHTML = str.toUpperCase();
} else {
alphas.item(i).innerHTML = str.toLowerCase();
}
}
return;
}
if (target.id == "keyspace") {
key = " ";
}
if (target.id == "keydel") {
key = "<<";
}
if (target.id == "keyenter") {
key = ">>";
}
if (key == "_") {
key = "us";
}
if (key == "&") {
key = "amp";
}
if (key == "%") {
key = "per";
}
if (key == "^") {
key = "carat";
}
if (key == "@") {
key = "at";
}
if (key == "#") {
key = "hash";
}
if (key == "{") {
key = "curlleft";
}
if (key == "}") {
key = "curlright";
}
if (key == "|") {
key = "pipe";
}
if (key == "\\") {
key = "backslash";
}
if (key == "<") {
key = "lt";
}
if (key == ">") {
key = "gt";
}
url = urlHome + "/?cmd=go";
url = url + "_" + key;
$.ajax({
url: url,
dataType: "jsonp",
crossDomain : true,
success: function (data) {
app = JSON.stringify(data);
console.log(JSON.stringify(app));
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log(textStatus);
},
timeout: 5000
});
});
function mousePosition() {
var position1 = $("#draggable").position();
var position2 = $("#mouse").position();
mouseHomeX = position1.left + position2.left;
mouseHomeY = position1.top + position2.top;
mouseX = mouseHomeX;
mouseY = mouseHomeY;
$("#draggable").css({position: "absolute", top: mouseHomeY, left: mouseHomeX});
}
/*$(document).on("touchmove", function (event) {
if (event.scale !== 1) { event.preventDefault(); }
}, false);
*/
$(document).on("drag", "#draggable", function(){
var offset = $(this).offset();
mouseX = offset.left - mouseX;
mouseY = offset.top - mouseY;
url = urlHome + "/?cmd=mouse_" + mouseX + "_" + mouseY;
$.ajax({
url: url,
dataType: "jsonp",
crossDomain : true,
success: function (data) {
console.log(JSON.stringify(data));
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log(textStatus);
},
timeout: 5000
});
mouseX = offset.left;
mouseY = offset.top;
});
$(document).on("dragstop", "#draggable", function(){
$("#draggable").css({top: mouseHomeY, left: mouseHomeX});
mouseX = mouseHomeX;
mouseY = mouseHomeY;
});
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class AlexaConnections {
ServerSocket server;
result users;
private class sockets {
private Socket client;
OutputStream os;
InputStream is;
sockets(Socket client, String license, String deviceId) {
this.client = client;
try {
os = client.getOutputStream();
is = client.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean sendData(byte[] bytes) {
boolean result = false;
try {
os.write(bytes);
os.flush();
result = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public void close() {
try {
System.out.println("Closing " + license);
license = "";
os.close();
is.close();
client.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private class JSONHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
call(exchange);
}
private synchronized void call(HttpExchange exchange) {
System.out.println("Server received");
new Thread(new JSONRunnable(exchange)).start();
}
}
private class JSONRunnable implements Runnable {
protected HttpExchange exchange = null;
public JSONRunnable(HttpExchange exchange) {
this.exchange = exchange;
}
@Override
public void run() {
try {
String requestMethod = exchange.getRequestMethod();
System.out.println(requestMethod);
Headers responseHeaders = exchange.getResponseHeaders();
OutputStream responseBody = exchange.getResponseBody();
String uri = exchange.getRequestURI().toString();
System.out.println(uri);
String query = exchange.getRequestURI().getQuery();
if (query == null) {
exchange.sendResponseHeaders(200, 0);
responseHeaders.set("Content-Type", "text/html");
responseBody.write("OK".getBytes());
responseBody.close();
return;
}
System.out.println(query);
processCommand(query);
int i = query.indexOf("callback=");
if (i >= 0) {
i +=9;
int j = query.indexOf("&", i);
String callback = "";
if (j > i) callback = query.substring(i, j);
System.out.println(callback);
exchange.sendResponseHeaders(200, 0);
responseHeaders.set("Content-Type", "text/json");
responseBody.write((callback + "({\"result\" : \"OK\"});").getBytes());
responseBody.close();
} else {
exchange.sendResponseHeaders(200, 0);
responseHeaders.set("Content-Type", "text/html");
responseBody.write("OK".getBytes());
responseBody.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void processCommand(String query) {
try {
int i = query.indexOf("addrs=");
int j = query.indexOf("&");
if (j < i || i < 0) {
return;
}
String addrs = query.substring(i+6, j);
System.out.println(addrs + " " + addrs.length());
i = query.indexOf("cmd=");
if (i < j) return;
String cmd = query.substring(i+4);
System.out.println(cmd);
for (j = 0; j < socketList.size(); ++j) {
if (socketList.get(j).client.isClosed()) {
continue;
}
System.out.println("Sending " + cmd
if (!socketList.get(j).sendData(cmd.getBytes())) {
socketList.get(j).close();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ArrayList<sockets> socketList;
AlexaConnections() {
socketList = new ArrayList<sockets>();
try {
InetSocketAddress addr = new InetSocketAddress(12345);
HttpServer httpserver = HttpServer.create(addr, 0);
httpserver.createContext("/", new JSONHandler());
httpserver.setExecutor(Executors.newCachedThreadPool());
httpserver.start();
System.out.println("HTTP Server is listening on port 12345");
server = new ServerSocket(54321);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
System.out.println("Waiting for connection");
Socket client = server.accept();
System.out.println("Connected From " + client.getRemoteSocketAddress().toString());
client.setSoTimeout(5000);
InputStream is = client.getInputStream();
try {
byte[] bytes = new byte[256];
int numberOfBytes = is.read(bytes, 0, 256);
System.out.println(numberOfBytes);
if (numberOfBytes > 0) {
String addrs = new String(bytes, 0, numberOfBytes);
addrs = addrs.replaceAll("\r", "");
addrs = addrs.replaceAll("\n", "");
System.out.println(addrs);
String deviceId = "";
socketList.add(new sockets(client, addrs, deviceId));
} else {
client.close();
}
} catch (Exception e) {
e.printStackTrace();
try {
System.out.println("Closing Connection");
is.close();
client.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, 500, 500);
Timer statusTimer = new Timer();
statusTimer.schedule(new TimerTask() {
@Override
public void run() {
for (int j = 0; j < socketList.size(); ++j) {
if (socketList.get(j).client.isClosed()) {
continue;
}
try {
byte[] bytes = new byte[64];
socketList.get(j).os.write("OM".getBytes());
int numberOfBytes = socketList.get(j).is.read(bytes);
if (numberOfBytes > 0) {
System.out.println("Received " + new String(bytes, 0, numberOfBytes);
}
} catch (SocketTimeoutException se) {
} catch (Exception ex) {
ex.printStackTrace();
socketList.get(j).close();
}
}
}
}, 500, 60000);
}
}
#define OPEN 1
#define CLOSE 0
#define ENABLE_PIN1 2
#define DIR_PIN1 3
#define STEP_PIN1 4
#define ENABLE_PIN2 5
#define DIR_PIN2 6
#define STEP_PIN2 7
#define SIGNAL_PIN 8
#define LIMIT_PIN 9
String inputString = "";
boolean stringComplete = false;
unsigned long steps = 0;
int previousState = LOW;
int currentState = LOW;
void setup() {
pinMode(STEP_PIN1, OUTPUT);
pinMode(ENABLE_PIN1, OUTPUT);
pinMode(DIR_PIN1, OUTPUT);
pinMode(STEP_PIN2, OUTPUT);
pinMode(ENABLE_PIN2, OUTPUT);
pinMode(DIR_PIN2, OUTPUT);
pinMode(SIGNAL_PIN, INPUT_PULLUP);
pinMode(LIMIT_PIN, INPUT_PULLUP);
digitalWrite(ENABLE_PIN1, HIGH);
delay(100);
digitalWrite(DIR_PIN1, HIGH);
delay(100);
digitalWrite(ENABLE_PIN1, HIGH);
digitalWrite(ENABLE_PIN2, HIGH);
delay(100);
digitalWrite(DIR_PIN2, HIGH);
delay(100);
digitalWrite(ENABLE_PIN2, HIGH);
previousState = digitalRead(SIGNAL_PIN);
currentState = previousState;
inputString.reserve(500);
Serial.begin(9600);
steps = 999999;
}
void loop() {
if (stringComplete) {
stringComplete = false;
processString();
}
currentState = digitalRead(SIGNAL_PIN);
if (currentState != previousState && currentState == HIGH){
previousState = currentState;
digitalWrite(ENABLE_PIN1, HIGH);
delay(100);
digitalWrite(DIR_PIN1, HIGH);
delay(100);
digitalWrite(ENABLE_PIN1, LOW);
digitalWrite(ENABLE_PIN2, HIGH);
delay(100);
digitalWrite(DIR_PIN2, HIGH);
delay(100);
digitalWrite(ENABLE_PIN2, LOW);
steps = 0;
}
if (currentState != previousState && currentState == LOW) {
previousState = currentState;
digitalWrite(ENABLE_PIN1, HIGH);
delay(100);
digitalWrite(DIR_PIN1, LOW);
delay(100);
digitalWrite(ENABLE_PIN1, LOW);
digitalWrite(ENABLE_PIN2, HIGH);
delay(100);
digitalWrite(DIR_PIN2, LOW);
delay(100);
digitalWrite(ENABLE_PIN2, LOW);
steps = 0;
}
if (steps < 55000) {
++steps;
rotate();
} else {
digitalWrite(ENABLE_PIN1, HIGH);
digitalWrite(ENABLE_PIN2, HIGH);
}
}
void processString() {
if (inputString.indexOf("UP") > 0) {
digitalWrite(ENABLE_PIN1, HIGH);
delay(100);
digitalWrite(DIR_PIN1, HIGH);
delay(100);
digitalWrite(ENABLE_PIN1, LOW);
digitalWrite(ENABLE_PIN2, HIGH);
delay(100);
digitalWrite(DIR_PIN2, HIGH);
delay(100);
digitalWrite(ENABLE_PIN2, LOW);
steps = 0;
}
if (inputString.indexOf("DOWN") > 0) {
digitalWrite(ENABLE_PIN1, HIGH);
delay(100);
digitalWrite(DIR_PIN1, LOW);
delay(100);
digitalWrite(ENABLE_PIN1, LOW);
digitalWrite(ENABLE_PIN2, HIGH);
delay(100);
digitalWrite(DIR_PIN2, LOW);
delay(100);
digitalWrite(ENABLE_PIN2, LOW);
steps = 0;
}
if (inputString.indexOf("STOP") > 0) {
digitalWrite(ENABLE_PIN1, HIGH);
digitalWrite(ENABLE_PIN2, HIGH);
steps = 999999;
}
Serial.write(inputString.c_str());
inputString = "";
}
void rotate() {
if (digitalRead(LIMIT_PIN) == LOW && digitalRead(DIR_PIN1) == HIGH) {
steps = 999999;
return;
}
digitalWrite(STEP_PIN1, HIGH);
digitalWrite(STEP_PIN2, HIGH);
delayMicroseconds(150);
digitalWrite(STEP_PIN1,LOW);
digitalWrite(STEP_PIN2,LOW);
delayMicroseconds(150);
}
void serialEvent() {
while (Serial.available()) {
char inChar = (char) Serial.read();
if (inChar == '$') {
inputString = "$";
} else {
if (inputString.length() < 498) {
inputString += inChar;
}
}
if (inChar == '\n' && inputString.startsWith("$")) {
stringComplete = true;
}
}
}
Comments