TA - References.docx

advertisement
References
1) “Elkahfi MCS-51 Microtainer”, Elkahfi (2005).
2) “MCS-51 Programmer’s Guide and Instruction Set”, Intel Corporation (1992).
3) “How to Implement I2C Communication Using Intel MCS-51
Microcontrollers”, Intel Corporation (1993).
4) Putra Agfianto Eko. “Belajar Mikrokontroler AT89S51/52/55 Teori dan
Aplikasi Edisi 2”, Penerbit Gava Media.
5) Raharjo, Budi; Heryanto, Imam; Haryono, Arif. “Tuntunan Pemrograman Java
untuk Handphone”, Penerbit Informatika (2007).
6) Keogh, Jim. “J2ME: The Complete Reference”, McGraw-Hill/Osborne
(2003).
7) Kofler, Michael. “The Definitive Guide to MySQL, Second Edition”, Apress
(2004).
8) Matthews, Mark; Cole, Jim; Gradecki, Joseph D. “MySQL and Java
Developer’s Guide” Wiley Publishing, Inc. (2002).
9) Haryanto, Bambang. “Esensi-esensi Bahasa Pemrograman Java” Penerbit
Informatika (2005).
10) “Fundamental of the Java Programming Language SL-110”, Sun
Microsystem.
11) “Java Programming Guide SL-275”, Sun Microsystem.
xii
PDF created with pdfFactory trial version www.pdffactory.com
40
Appendix A
Operation Sequence Diagrams
In order to understand the process between object when a particular operation
eventuates, some operations such as device activation by SMS, intruder alert,
status checking and device activation are explained by following sequence
diagrams:
1. Device activation by SMS sequences:
2. Device activation by GUI process:
PDF created with pdfFactory trial version www.pdffactory.com
41
3. Intruder alert sequences:
4. Status checking sequences:
PDF created with pdfFactory trial version www.pdffactory.com
42
Appendix B
Operation Flowcharts
The J2SE program used Java Communication API to perform input listening and
output writing process from/to microcontroller, it also used JDBC API to read and
write MySQL tables. The detail steps of those operations explained by the
following flowcharts:
1. Outbox, inbox and home_automation log tables data writing process:
PDF created with pdfFactory trial version www.pdffactory.com
43
2. PC to microcontroller data sending process:
PDF created with pdfFactory trial version www.pdffactory.com
44
3. Microcontroller to PC data retrieval process:
PDF created with pdfFactory trial version www.pdffactory.com
45
4. Inbox table data retrieval process:
PDF created with pdfFactory trial version www.pdffactory.com
46
Appendix C
Program Codes
This Home Automation System uses Assembly, J2SE and J2ME softwares to do
all operations. This section provides the program codes applied in this system.
1. Assembly program:
DATA0
EQU
40H
ORG
ACALL
ACALL
ACALL
ZERO
DELAY1S
ZERO
SETB
SETB
SETB
ACALL
SJMP
EA
EX1
IT1
INITIAL
START
ORG
MOV
MOV
JNB
CLR
ACALL
RETI
00H
; Subrutin utk membuat P2 = 0
13H
A, #'P'
SBUF, A
TI, $
TI
; (ASCII 37 = 7h) keluaran"7" pada PC menandakan ada penyusup
DELAY1S
START:
JNB
ACALL
ACALL
ACALL
SJMP
RI, START
TERIMA
KIRIM
SCANMASUKAN
START
TERIMA:
JNB
CLR
MOV
RI, EXITTERIMA
RI
A, SBUF
EXITTERIMA:
RET
KIRIM:
MOV
JNB
CLR
RET
SBUF, A
TI, $
TI
MOV
R3, #10
MOV
R2, #100
MOV
R1, #100
DELAY1S:
LOOP3:
LOOP2:
LOOP1:
NOP
NOP
NOP
NOP
PDF created with pdfFactory trial version www.pdffactory.com
; cek kalau ada data dari PC
; penerimaan data selesai
; ambil data dari buffer
47
NOP
NOP
NOP
NOP
NOP
DJNZ
DJNZ
DJNZ
RET
R1, LOOP1
R2, LOOP2
R3, LOOP3
ZERO:
; Rutin utk men-set default port menjadi 0 bila tdk ada masukan
MOV
RET
P2, 0
MOV
MOV
SETB
MOV
MOV
MOV
SETB
RET
SCON, #50H
A, PCON
ACC.7
PCON, A
TMOD, #20H
TH1, #0FDH
INITIAL:
TR1
; mode serial
; setting utk 2 x baudrate
; setting mode Timer 1 mode 2 (autoreload)
; setting baudrate = 9600 x 2 = 19200bps
; mulai aktifkan Timer 1
SCANMASUKAN:
CJNE
SETB
SJMP
A, #'A', LAMPUOFF
; Bila ada masukan 1 dari PC
P2.0
; Port 2.0 high, bila tdk cek subrutin lain
EXITSCANMASUKAN
; Kembali ke rutin utama
CJNE
CLR
SJMP
A, #'Z', IRON
; Bila ada masukan 4 dari PC
P2.0
; Port 2.0 low, bila tdk cek subrutin lain
EXITSCANMASUKAN ; Kembali ke rutin utama
CJNE
SETB
SJMP
A, #'S', IROFF
; Bila ada masukan 2 dari PC
P2.1
; Port 2.1 high, bila tdk cek subrutin lain
EXITSCANMASUKAN ; Kembali ke rutin utama
CJNE
CLR
SJMP
A, #'X', ALARMON
; Bila ada masukan 5 dari PC
P2.1
; Port 2.1 low, bila tdk cek subrutin lain
EXITSCANMASUKAN ; Kembali ke rutin utama
CJNE
SETB
SJMP
A, #'D', ALARMOFF
; Bila ada masukan 3 dari PC
P2.2
; Port 2.2 high, bila tdk cek subrutin lain
EXITSCANMASUKAN ; Kembali ke rutin utama
CJNE
CLR
SJMP
A, #'C', CEKLAMPU
; Bila ada masukan 6 dari PC
P2.2
; Port 2.2 low, bila tdk cek subrutin lain
EXITSCANMASUKAN ; Kembali ke rutin utama
LAMPUOFF:
IRON:
IROFF:
ALARMON:
ALARMOFF:
CEKLAMPU:
CJNE
JB
ACALL
KIRIMLAMPUON:
ACALL
MOV
MOV
JNB
CLR
SJMP
KIRIMLAMPUOFF:
ACALL
MOV
MOV
JNB
CLR
ACALL
A, #'Q', CEKIR
; Bila ada masukan "7" dari PC
P2.0, KIRIMLAMPUON ; Cek P2.0 high/low, Bila high ke rutin KIRIMLAMPUON
KIRIMLAMPUOFF
; Bila low ke rutin KIRIMLAMPUOFF
DELAY1S
A, #'A'
; Bila P2.0 high kirim data "1" ke PC
SBUF, A
TI, $
TI
EXITSCANMASUKAN
DELAY1S
A, #'Z'
SBUF, A
TI, $
TI
START
; Bila P2.0 low kirim data "4" ke PC
CEKIR:
CJNE
A, #'W', CEKALARM
PDF created with pdfFactory trial version www.pdffactory.com
; Bila ada masukan "8" dari PC
48
JB
P2.1, KIRIMIRON
; Cek P2.1 high/low, Bila high ke rutin
KIRIMIRON
ACALL
KIRIMIRON:
ACALL
MOV
MOV
JNB
CLR
SJMP
KIRIMIROFF:
ACALL
MOV
MOV
JNB
CLR
ACALL
KIRIMIROFF
DELAY1S
A, #'S'
SBUF, A
TI, $
TI
EXITSCANMASUKAN
DELAY1S
A, #'X'
SBUF, A
TI, $
TI
START
; Bila low ke rutin KIRIMIROFF
; Bila P2.1 high kirim data "2" ke PC
; Bila P2.1 low kirim data "5" ke PC
CEKALARM:
CJNE
JB
A, #'E', EXITSCANMASUKAN
P2.2, KIRIMALARMON
; Bila ada masukan "8" dari PC
; Cek P2.1 high/low, Bila high ke rutin
KIRIMALARMOFF
; Bila low ke rutin KIRIMALARMOFF
KIRIMALARMON
ACALL
KIRIMALARMON:
ACALL
MOV
MOV
JNB
CLR
SJMP
KIRIMALARMOFF:
ACALL
MOV
MOV
JNB
CLR
ACALL
DELAY1S
A, #'D'
SBUF, A
TI, $
TI
EXITSCANMASUKAN
DELAY1S
A, #'C'
SBUF, A
TI, $
TI
START
; Bila P2.2 high kirim data "3" ke PC
; Bila P2.2 high kirim data "6" ke PC
EXITSCANMASUKAN:
RET
END
2. J2ME software:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.wireless.messaging.*;
import javax.microedition.io.*;
import java.io.*;
public class Home3 extends MIDlet implements CommandListener, Runnable
{
private Display display;
private List list;
private Command cmdRequest, cmdSubmit, cmdExit;
private TextBox tfPin;
private Alert alert;
private String a="5555";
private Thread thread;
private Ticker tickerPin, tickerList;
private String textTickerPin= "Enter password to clarify your security clearence";
private String textTickerList= "Welcome Mr. Erik Sentosa. Please select a command";
public Home3()
{
display
= Display.getDisplay(this);
cmdRequest = new Command("Request", Command.OK, 2);
cmdSubmit = new Command("Submit", Command.OK, 2);
cmdExit
= new Command("Exit", Command.EXIT, 1);
alert
= new Alert(null);
}
PDF created with pdfFactory trial version www.pdffactory.com
49
public void startApp()
{
tfPin
}
= generatePinInput();
public List generateList()
{
list = new List("Home Automation Controller", Choice.EXCLUSIVE);
tickerList = new Ticker(textTickerList);
list.setTicker(tickerList);
list.append("Turn ON IR sensor", null);
list.append("Turn OFF IR sensor", null);
list.append("Check IR sensor status", null);
list.append("Turn ON siren", null);
list.append("Turn OFF siren", null);
list.append("Check siren status", null);
list.append("Turn ON lights", null);
list.append("Turn OFF lights", null);
list.append("Check lights status", null);
list.addCommand(cmdRequest);
list.addCommand(cmdExit);
list.setCommandListener(this);
display.setCurrent(list);
return list;
}
public void run()
{
MessageConnection conn = null;
String addr = "sms://081910581861";
try
{
conn = (MessageConnection) Connector.open(addr);
TextMessage msg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setAddress(addr);
int indeks = list.getSelectedIndex();
if
(indeks == 0) {msg.setPayloadText("A");}
else if
(indeks == 1) {msg.setPayloadText("Z");}
else if
(indeks == 2) {msg.setPayloadText("Q");}
else if
(indeks == 3) {msg.setPayloadText("S");}
else if
(indeks == 4) {msg.setPayloadText("X");}
else if
(indeks == 5) {msg.setPayloadText("W");}
else if
(indeks == 6) {msg.setPayloadText("D");}
else if
(indeks == 7) {msg.setPayloadText("C");}
else if
(indeks == 8) {msg.setPayloadText("E");}
conn.send(msg);
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
if (conn != null)
{
try
{
conn.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
public void pauseApp()
{}
public void destroyApp(boolean unconditional)
{ notifyDestroyed(); }
public void commandAction(Command c, Displayable s)
{
if (c == cmdExit)
{destroyApp(true);}
else if(c == cmdSubmit)
PDF created with pdfFactory trial version www.pdffactory.com
50
{
if(tfPin.getString().equals(a))
{
list = generateList();
}
else
{
alert.setType(AlertType.WARNING);
alert.setString("Wrong password");
alert.setTimeout(1000);
display.setCurrent(alert, tfPin);
}
}
else if(c == cmdRequest)
{
try
{
thread = new Thread(this);
thread.start();
}
catch(Exception e)
{e.printStackTrace();}
}
}
public TextBox generatePinInput()
{
TextBox tfPin
= new TextBox("Your password is:", null, 20, TextField.PASSWORD);
tickerPin
= new Ticker(textTickerPin);
tfPin.setTicker(tickerPin);
tfPin.addCommand(cmdSubmit);
tfPin.addCommand(cmdExit);
tfPin.setCommandListener(this);
display.setCurrent(tfPin);
return tfPin;
}
}
3. J2SE softwares:
The Main.class:
package homeautomation;
import java.io.*;
public class HomeAutomationMainClass extends Thread{
public static void main(String Args[])
{
new SMSListener();
new GUI();
SerialListener SL = new SerialListener();
while(true){
if (SL.boo == false)
{
try{Thread.sleep(600);
}
catch(InterruptedException e){
System.out.println("Thread gak bisa");
}
SL.getPort();
}
}
}
}
PDF created with pdfFactory trial version www.pdffactory.com
51
The Log.class:
package homeautomation;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Log
{
String actionMade;
public Log(String stringToPhoneToTable)
{
System.out.println("["+new java.util.Date() +"] HomeAutomationLog:"+stringToPhoneToTable);
this.actionMade=stringToPhoneToTable;
writeLog();
}
public void writeLog()
{ try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost:3306/sms?user=root&password=erik");
java.sql.PreparedStatement statement = connection.prepareStatement
("INSERT INTO home_automation_log (`action`) VALUES (?)");
statement.setString(1, actionMade);
statement.executeUpdate();
connection.close();
}
catch(ClassNotFoundException ex){ex.printStackTrace();}
catch(InstantiationException ex){ex.printStackTrace();}
catch(IllegalAccessException ex){ex.printStackTrace();}
catch(SQLException ex){ex.printStackTrace();}
}
}
The SMSListener.class:
package homeautomation;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SMSListener extends Thread{
// Atribut untuk jdbc
private java.sql.Connection connection;
private java.sql.Statement statement;
private java.sql.ResultSet result;
public SMSListener() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sms?user=root&password=erik");
statement = this.connection.createStatement();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (java.sql.SQLException ex) {
ex.printStackTrace();
}
this.start();
}
public void run(){
System.out.println(" TEST ");
System.out.println(" ");
System.out.println(" ");
while(true){
try {
PDF created with pdfFactory trial version www.pdffactory.com
52
this.result = statement.executeQuery
("SELECT TextDecoded, SenderNumber, ReceivingDateTime, Processed, ID FROM inbox WHERE Processed='false'");
while(result.next()){
System.out.println("["+new java.util.Date()+"] "+result.getString("ID")+" "+result.getString("TextDecoded"));
new MicrocontrollerManager(result.getString("TextDecoded"), result.getString("ID"));
}
}catch (SQLException ex) {
ex.printStackTrace();
}
try {
this.sleep(5000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
The TablesManager.class:
package homeautomation;
import homeautomation.Log;
import java.sql.*;
public class HomeAutomationTablesManager {
public String getSMSFromTable()
{
String inputTextFromPhone = "";
try
{ Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sms?user=root&password=erik");
java.sql.PreparedStatement statement = connection.prepareStatement("SELECT TextDecoded FROM inbox WHERE
Processed='false'");
java.sql.ResultSet rs = statement.executeQuery();
java.sql.PreparedStatement statement2 = connection.prepareStatement("UPDATE inbox SET Processed='true' WHERE
Processed='false'");
statement2.executeUpdate();
new Log("New command from phone: " + inputTextFromPhone);
while(rs.next()){
System.out.println(rs.getString("TextDecoded"));
inputTextFromPhone = rs.getString("TextDecoded");
}
connection.close();
}
catch(ClassNotFoundException ex){ex.printStackTrace();}
catch(InstantiationException ex){ex.printStackTrace();}
catch(IllegalAccessException ex){ex.printStackTrace();}
catch(SQLException ex){ex.printStackTrace();}
return inputTextFromPhone;
}
public void sendSMSToTable (String outputStringFromMicrocontroller)
{
String outputTextToPhone ="";
System.out.println("Sms dari mikro"+outputStringFromMicrocontroller);
if(outputStringFromMicrocontroller.startsWith("D"))
{outputTextToPhone ="Lights on";sendreply(outputTextToPhone);}
else if (outputStringFromMicrocontroller.startsWith("C"))
{outputTextToPhone ="Lights off";sendreply(outputTextToPhone);}
else if (outputStringFromMicrocontroller.startsWith("A"))
{outputTextToPhone ="IR sensor active";sendreply(outputTextToPhone);}
else if (outputStringFromMicrocontroller.startsWith("Z"))
{outputTextToPhone ="IR sensor inactive";sendreply(outputTextToPhone);}
else if (outputStringFromMicrocontroller.startsWith("S"))
{outputTextToPhone ="Siren active";sendreply(outputTextToPhone);}
else if (outputStringFromMicrocontroller.startsWith("X"))
{outputTextToPhone ="Siren inactive";sendreply(outputTextToPhone);}
else if (outputStringFromMicrocontroller.startsWith("P"))
{
outputTextToPhone ="Intruder alert!";
try
{
PDF created with pdfFactory trial version www.pdffactory.com
53
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sms?user=root&password=erik");
//Utk menyalakan lampu
java.sql.PreparedStatement statement3 = connection.prepareStatement
("INSERT INTO `inbox` ( `UpdatedInDB` , `ReceivingDateTime` , `Text` , `SenderNumber` , `Coding` , `UDH` ,
`SMSCNumber` , `Class` , `TextDecoded` , `RecipientID` , `Processed`) "+
"VALUES (NOW( ) , '0000-00-00 00:00:00', ' ' , '081910581861', '8bit', '0000' , '1', '-1', 'D' , '1', 'false')");
//statement.setString(1, outputTextToPhone);
statement3.executeUpdate();
//Utk menyalakan sirene
java.sql.PreparedStatement statement4 = connection.prepareStatement
("INSERT INTO `inbox` ( `UpdatedInDB` , `ReceivingDateTime` , `Text` , `SenderNumber` , `Coding` , `UDH` ,
`SMSCNumber` , `Class` , `TextDecoded` , `RecipientID` , `Processed`) "+
"VALUES (NOW( ) , '0000-00-00 00:00:00', ' ' , '081910581861', '8bit', '0000' , '1', '-1', 'S' , '1', 'false')");
statement4.executeUpdate();
connection.close();
//new HomeAutomationLog("SMS sent to phone: " + outputTextToPhone);
}
catch(ClassNotFoundException ex){ex.printStackTrace();}
catch(InstantiationException ex){ex.printStackTrace();}
catch(IllegalAccessException ex){ex.printStackTrace();}
catch(SQLException ex){ex.printStackTrace();}
}
else
{outputTextToPhone ="Invalid command: " + "'" + outputStringFromMicrocontroller +"'";}
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost:3306/sms?user=root&password=erik");
java.sql.PreparedStatement statement = connection.prepareStatement
("INSERT INTO `outbox` ( `UpdatedInDB` , `InsertIntoDB` , `SendingDateTime` , `Text` , `DestinationNumber` , `Coding` ,
`UDH` , `Class` , `TextDecoded` , `ID` , `MultiPart` , `RelativeValidity` , `SenderID` , `SendingTimeOut` , `DeliveryReport` , `CreatorID` )
"+
"VALUES (NOW( ) , '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL , '08562168994', 'Default_No_Compression', NULL ,
'-1', ? , NULL , 'true', '-1', NULL , '0000-00-00 00:00:00', 'default', '1')");
System.out.println("\n !!! Mengirim ke HP \n");
statement.setString(1, outputTextToPhone);
statement.executeUpdate();
connection.close();
new Log("SMS sent to phone: " + outputTextToPhone);
}
catch(ClassNotFoundException ex){ex.printStackTrace();}
catch(InstantiationException ex){ex.printStackTrace();}
catch(IllegalAccessException ex){ex.printStackTrace();}
catch(SQLException ex){ex.printStackTrace();}
}
public void sendreply(String outputTextToPhone){
try
{
System.out.println("sendreply():"+outputTextToPhone);
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sms?user=root&password=erik");
java.sql.PreparedStatement statement = connection.prepareStatement
("INSERT INTO `outbox` ( `UpdatedInDB` , `InsertIntoDB` , `SendingDateTime` , `Text` , `DestinationNumber` , `Coding` ,
`UDH` , `Class` , `TextDecoded` , `ID` , `MultiPart` , `RelativeValidity` , `SenderID` , `SendingTimeOut` , `DeliveryReport` , `CreatorID` )
"+
"VALUES (NOW( ) , '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL , '08562168994', 'Default_No_Compression',
NULL , '-1', ? , NULL , 'true', '-1', NULL , '0000-00-00 00:00:00', 'default', '1')");
System.out.println("\n !!! Mengirim ke HP \n");
statement.setString(1, outputTextToPhone);
statement.executeUpdate();
connection.close();
new Log("SMS sent to phone: " + outputTextToPhone);
PDF created with pdfFactory trial version www.pdffactory.com
54
}
catch(ClassNotFoundException ex){ex.printStackTrace();}
catch(InstantiationException ex){ex.printStackTrace();}
catch(IllegalAccessException ex){ex.printStackTrace();}
catch(SQLException ex){ex.printStackTrace();}
}
}
The SerialListener. class with MyResolver.class inner class
package homeautomation;
import java.io.*;
import java.util.*;
import javax.comm.*;
public class SerialListener implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
//static CommPortOwnershipListener listener;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
public boolean boo;
public SerialListener()
{
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements())
{
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
if (portId.getName().equals("COM1"))
{
try
{
portId.addPortOwnershipListener(new MyResolver());
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
}catch (PortInUseException e) {}
try
{
inputStream = serialPort.getInputStream();
}catch (IOException e) {}
try
{
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
try
{
serialPort.setSerialPortParams( 19200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);
readThread.start();
}
}
}
}
class MyResolver implements CommPortOwnershipListener{
protected boolean owned = false;
public void ownershipChange(int whaHoppen) {
switch (whaHoppen){
case PORT_OWNED:
//System.out.println("An open succeeded.");
owned = true;
boo = true;
break;
case PORT_UNOWNED:
//System.out.println("A close succeeded.");
owned = false;
break;
case PORT_OWNERSHIP_REQUESTED:
if (owned) {
PDF created with pdfFactory trial version www.pdffactory.com
55
serialPort.close();
boo = false;
owned = false;
} else {
System.out.println("Somebody else has the port");
}
}
}
}
public void run()
{
try
{
Thread.sleep(20000);
} catch (InterruptedException e) {}
}
public void getPort(){
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements())
{
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
if (portId.getName().equals("COM1"))
{
try
{
// portId.addPortOwnershipListener(new MyResolver());
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
}catch (PortInUseException e) {}
try
{
inputStream = serialPort.getInputStream();
}catch (IOException e) {}
try
{
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
try
{
serialPort.setSerialPortParams( 19200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);
readThread.start();
}
}
}
}
public void serialEvent(SerialPortEvent event)
{
switch(event.getEventType())
{
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20];
try
{
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
}
//System.out.println("6 - OK");
String temp = new String(readBuffer);
System.out.print(temp);
new HomeAutomationTablesManager().sendSMSToTable(temp);
PDF created with pdfFactory trial version www.pdffactory.com
56
}
catch (IOException e)
{}
break;
}
}
}
The MicrocontrollerManager.class:
package homeautomation;
import java.io.*;
import java.util.*;
import javax.comm.*;
import java.sql.DriverManager;
public class MicrocontrollerManager extends Thread
{
// Atribut dari javax.com
static Enumeration portList;
static CommPortIdentifier portId;
static SerialPort serialPort;
static OutputStream outputStream;
// -------------------------Thread readThread;
InputStream inputStream;
private java.sql.Connection connection;
private java.sql.Statement statement;
private java.sql.ResultSet result;
private java.sql.PreparedStatement preparedstatement;
private String inputStringToMicrocontroller;
private String smsID;
private boolean dariSMS;
public MicrocontrollerManager(String TextDecoded, String smsID)
{
new HomeAutomationLog("Menerima pesan dari: "+TextDecoded +" "+smsID);
this.dariSMS=true;
this.inputStringToMicrocontroller=TextDecoded;
this.smsID=smsID;
this.run();
}
public MicrocontrollerManager(String untuk_dikirim_keRS232)
{
new HomeAutomationLog("Perintah dari GUI: "+untuk_dikirim_keRS232);
this.dariSMS=false;
this.inputStringToMicrocontroller=untuk_dikirim_keRS232;
this.run();
//this.destroy();
}
public void run(){
System.out.println(this.dariSMS);
if(this.dariSMS){this.isProcessed();}
//Sebelum menulis pastikan tidak dipakai oleh serial listener
portList = CommPortIdentifier.getPortIdentifiers();
System.out.println("Test "+ portList.hasMoreElements());
while (portList.hasMoreElements())
{
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
if (portId.getName().equals("COM1"))
{
//System.out.println("Test 2");
try
{
serialPort = (SerialPort)
portId.open("SimpleWriteApp", 2000);
//System.out.println("1-OK");
} catch (PortInUseException e) {System.out.println("1-KAGA OK");}
try
{
PDF created with pdfFactory trial version www.pdffactory.com
57
outputStream = serialPort.getOutputStream();
//System.out.println("2-OK");
} catch (IOException e) {System.out.println("2-KAGA OK");}
try
{
serialPort.setSerialPortParams( 19200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
//System.out.println("3-OK");
}catch (UnsupportedCommOperationException e) {System.out.println("3-KAGA OK");}
try
{
outputStream.write(inputStringToMicrocontroller.getBytes());
//System.out.println("4-OK");
} catch (IOException e) {System.out.println("4-KAGA OK");}
}
}
}
// try
//{
serialPort.close();
//}
// catch (PortInUseException e) {System.out.println("Code baru error bwh");}
}
private void isProcessed(){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sms?user=root&password=erik");
preparedstatement = this.connection.prepareStatement("UPDATE inbox SET UpdatedInDB=NOW( ) ,Processed ='true' WHERE
`ID` =? LIMIT 1 ");
preparedstatement.setString(1, this.smsID);
preparedstatement.executeUpdate();
connection.close();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (java.sql.SQLException ex) {
ex.printStackTrace();
}
}
}
The GUI.class:
package homeautomation;
import homeautomation.MicrocontrollerManager;
public class GUI extends javax.swing.JFrame {
public GUI() {
initComponents();
System.out.println("YET");
this.setVisible(true);
}
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
PDF created with pdfFactory trial version www.pdffactory.com
58
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(0, 0, 0));
setForeground(new java.awt.Color(0, 0, 0));
setMinimumSize(new java.awt.Dimension(800, 500));
setResizable(false);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 680, 290));
jButton1.setText("IR Sensor On (A)");
jButton1.setMaximumSize(new java.awt.Dimension(80, 40));
jButton1.setMinimumSize(new java.awt.Dimension(80, 40));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 310, 130, 40));
jButton2.setText("IR Sensor Off (Z)");
jButton2.setMaximumSize(new java.awt.Dimension(80, 40));
jButton2.setMinimumSize(new java.awt.Dimension(80, 40));
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 370, 130, 40));
jButton3.setText("Siren On (S)");
jButton3.setMaximumSize(new java.awt.Dimension(80, 40));
jButton3.setMinimumSize(new java.awt.Dimension(80, 40));
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
getContentPane().add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 310, 140, 40));
jButton4.setText("Siren Off (X)");
jButton4.setMaximumSize(new java.awt.Dimension(80, 40));
jButton4.setMinimumSize(new java.awt.Dimension(80, 40));
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 370, 140, 40));
jButton5.setText("Light On (D)");
jButton5.setMaximumSize(new java.awt.Dimension(80, 40));
jButton5.setMinimumSize(new java.awt.Dimension(80, 40));
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
getContentPane().add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 310, 150, 40));
jButton6.setText("Light Off (C)");
jButton6.setMaximumSize(new java.awt.Dimension(80, 40));
jButton6.setMinimumSize(new java.awt.Dimension(80, 40));
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
getContentPane().add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 370, 150, 40));
pack();
}// </editor-fold>
PDF created with pdfFactory trial version www.pdffactory.com
59
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.append(new java.util.Date().toString()+ ": GUI - IR on button pressed\n" );
new MicrocontrollerManager("A");
new Log("GUI - IR on button pressed " );
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.append(new java.util.Date().toString()+ ": GUI - IR off button pressed\n" );
new MicrocontrollerManager("Z");
new Log("GUI - IR off button pressed");
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.append(new java.util.Date().toString()+ ": GUI - Siren on button pressed\n" );
new MicrocontrollerManager("S");
new Log("GUI - Siren on button pressed");
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.append(new java.util.Date().toString()+ ": GUI - Siren off button pressed\n" );
new MicrocontrollerManager("X");
new Log("GUI - Siren off button pressed");
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.append(new java.util.Date().toString()+ ": GUI - Light on button pressed\n" );
new MicrocontrollerManager("D");
new Log("GUI - Light on button pressed");
}
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.append(new java.util.Date().toString()+ ": GUI - Light off button pressed\n" );
new MicrocontrollerManager("C");
new Log("GUI - Light off button pressed");
}
// Variables declaration
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
PDF created with pdfFactory trial version www.pdffactory.com
Download