grad._report_2_final

advertisement
ABSTRACT
The demand on higher data rates in wireless data telecommunication in Palestine
is increasing day after another, but due to some technical issues, neither 3G nor 4G are
applicable in Palestine. From our point of view, this problem can be solved using Li-Fi.
Light Fidelity (Li-Fi) is a new technology that uses visible light spectrum to send and
receive data. If we use Li-Fi connection nodes connected to each light bulb in the street,
with some considerations to avoid interference, mobility, noise… Etc, the need for higher
data rates is satisfied. Li-Fi mainly consist of a light bulb sending pulses using light
intensity modulation and a visible light sensor at the receiver side to detect the signal and
demodulate it to pulses. Advantages to such technology are mainly stated in high speed,
low interference, and cost economic data connection. Moreover, it uses the same light
used for lighting to send data. Disadvantages to this technology are mainly concentrated
in need for line of sight, influence of sun light and other ambient lights around. In this
project we will build hardware circuits for Li-Fi nodes and Li-Fi clients, try to eliminate
the ambient light effect, and try to use this technology to establish an internet connection.
By this end, we can promise that the problem is solved efficiently.
1|Page
CHAPTER 1: Introduction
Recently, and due to quick technology evolution, and the need for mobile
communications to replace the old-fashioned fixed ones to allow mobility and flexibility
in communication everywhere, the need for higher speed communication became
obstructive. For the data transfer process, wired communication made a huge revolution
and achieved a lot of progress. Although, a day after another the need for higher data rate
technologies become urgent. Due to this reason, scientists and experts work hard to find
new techniques to serve out the largest number of users with higher transmission data rate
and free to move technique. 3G, 4G, Wi-Fi and other technologies can permanently do
that, but as time goes, the necessity to transmit and receive data with much higher data
rate, faster, more secure and cheaper technique is desired. For new and more
sophisticated technique, as any current one, a range of frequencies is mainly required. But
recently, frequency spectrum becomes fully used for other applications. So, we are
looking for exploiting the un-used range of frequencies in order to solve the RF
bandwidth limitation problem. From this point, we find that the range between 405THz to
790THz (visible light range) is un-exploited so we trend to use it to invent a new
effective technology which is Li-Fi (light fidelity) technology.
Figure 1 shows the frequency spectrum and the used and the un-used frequency
ranges (1):
Figure 1 Frequency spectrum
Li-Fi (Light Fidelity) is a new technique which uses visible light communication
(VLC) for transmitting data through a LED light bulb by varying the light intensity faster
than the human eye can follow. If the LED is one then the receiver registers a binary 1,
otherwise logic zero is registered (2). This technique has a lot of advantages some of them
are:
2|Page
1.1 ADVANTAGES (3)







It carries much more information compared with Wi-Fi, 3G and 4G.
An excellent solution for the bandwidth limitation.
High data rate exceeds 10 Gb/s.
More secure with lower cost.
Does not cause electromagnetic interference.
Low power consumption.
It leads to internet of things.
On the other hand, we expect to face some challenges such as:
1.2 CHALLENGES (3)



Presence of day light.
Need for line of sight process.
Interference with other light sources.
As a comparison between Wi-Fi and Li-Fi technologies (4):
Table 1 Comparison between LiFi and WiFi
3|Page
CHAPTER 2: Literature Review
Light Fidelity or what is called Li-Fi or Visible Light Communication (VLC) was
first brought to the world by Professor Harald Haas, Chair of Mobile Communications at
school of Engineering, University of Edinburgh( 5), who demonstrated the data
transmission over light live on stage at TED Global in July 2011.
Before that, the first blink of optical wireless communication was in 2008 by a
project known as D-Light Project (4).D-Light Project was first launched in January of
2010 at University of Edinburgh. It made a lot of Progress in optical wireless
communication and improved coding schemes to obtain higher data rates. The D-Light
Project achieved a bit-rate of 102.5Mbit/s under normal light conditions, over a distance
between 1-4 m, using an off-the-shelf 18 watt Osram Ostar white LED lamp, and
achieved an error rates below 1:10,000( 6).
After that, in 2012 Pure LiFi was born from the University of Edinburgh, which
concentrates its researches on optical wireless communications to improve it and
provides higher data rates (4).
2.1 How VLC Works
The LED is made of Semiconductors, and thus it is affected by the current passes
through it. When the current flows through the LED, it emits a stream of photons, which
is the visible light seen by human eye.
If the current increases or decreases, the intensity of the emitted photons varies.
Thus, VLC uses this property to modulate data pulses and send it over light in a very high
speed that human eye can’t recognize, which is known as Intensity Modulation. The
Figure 2 below illustrates how VLC works (7).
Figure 2 how VLC works
4|Page
2.2 VLC Architecture
As stated in the proposal submitted by Samsung and ETRI to the IEEE 802.15
Working Group for Wireless Personal Area Networks, which discusses the PHY and
MAC layers of the VLC, the VLC standard IEEE 802.15.7 states that the sending part of
VLC must have PHY/MAC functions for illumination and transmission performance,
while the receiving part can use any PD with maintaining the avoidance of light
interference (8).
As shown in Figure 3, the architecture takes in consideration the lighting beside
the data, and that’s an advantage for VLC that applies the functions of data transmission
and lighting.
Figure 3 VLC Architecture
5|Page
2.3 Optical Angle
The optical angle is the angle which the light spreads in, and it is normal to the
surface of the optical port (LED).
The optical angle can give an indication of the distance that the light can travel
with accepted power level to maintain the connection. If the angle is lower, the light is
then more intense and can travel farther distance, and that’s why laser can reach farther
distances than regular light bulb.
The Figure 4 illustrates the optical angle.
Figure 4 Optical Angle
At Tx, this angle is called Divergence Angle.
At Rx, this angle is called FOV (Field Of View).
These angles can be controlled mechanically using collecting lenses. For higher
data rates, narrower divergence angle and wider FOV are required (9).
2.4 Modulation
For VLC, there are several modulation schemes that are used in high data rate
PHY layer. CCM, HHW, OOK and V-PPM are some kind of those schemes.
Moreover, there are several types of LED’s that can be used, such like RGB LED
and white LED (yellow Phosphor) which is more popular than RGB LED due to its price,
although it gives lower data rate than RGB due to response time of Phosphor material,
but it can support all kind of connections (single, half duplex and full duplex).
2.4.1 OOK
OOK (On-OFF-Keying) is a form of ASK Modulation scheme but in its simplest
form. It simply turns the carrier on or off depending on the data bits.
OOK doesn’t require prior acknowledgment of transmitter and receiver, and it is
used for link establishment, beacon and device discovery.
The Figure 5 shows the OOK modulation scheme (10).
6|Page
Figure 5 OOK Modulation
2.4.2 CCM (Color Code Modulation)
CCM is a new modulation scheme proposed for VLC, and it is expected to give
more flexibility to the VLC system better than WDM because it doesn’t depend on ʎ
directly. The Figure 6 is an example of CCM, which can send 2 bits per symbol.
Figure 6 Example of CCM modulation
7|Page
The system in Figure 6 is called CIE1931. Each color has defined values of x and
y. the numbers around the color palette is the wavelengths of colors.
The relation between x, y and the RGB are stated in the following equations:
X = 2.7689R + 1.7517G + 1.1302B
Y = R + 4.5907G + 0.0601B
Z = 0.0565G + 5.5943B
x = X/(X + Y + Z)
y = Y/(X + Y + Z)
R, G, B: the red, green and blue wavelengths of each symbol respectively.
The colors are made using RGB LED source, by using intensity ratio, not as each
RGB absolute value. CCM is used for data modulation (11).
2.4.3 HHW (High Hamming Weight)
To improve illumination function, the average voltage level must be high. To do
such thing, HHW is used.
HHW forces the channel encoder to select codewords with high hamming weight;
that means the output codeword will contain logic 1’s as much as possible, and by default
the average voltage level is increased (12).
The block diagram in Figure 7 shows the HHW system.
Figure 7 HHW Block diagram
2.4.4 V-PPM (Variable Pulse Position Modulation)
For the best illumination, three factors must be maintained; those are the nonflickering, dimming control and full brightness.
The flickering LED is not good for eye safety, so we need a modulation scheme
that removes the flickering. Otherwise, VLC is not suitable for illumination.
Moreover, the dimming function is also mandatory for illumination; it maintains
smooth increase and decrease in illumination to deliver the best lighting function.
Finally, the full brightness is needed also for illumination; the modulation scheme
reduces the maximum brightness of the LED and so we need a modulation scheme that
provides brightness as near as possible to a LED used for illumination only.
To maintain these three factors, we need to control the pulse position to remove
flickering, control the dimming and provide as much brightness as possible (13).
Figures 8 and 9 are two examples of PPM.
8|Page
Figure 8 Example of PPM
Figure 9 Example of PPM
9|Page
CHAPTER 3: Methodology
In our approach, we used our own designed circuit for both transmitter and receiver.
In our design, we used OOK modulation scheme in its simplest form, at a bit rate of 300
Bps.
In the first phase our methodology was used for proof of concept with a bit rate equals to
300 Bps, and the second phase of the project introduces some enhancement on the
circuits like increasing the distance, preparing the system to handle several types of data
(audio, video …etc), decreasing the operational energy of the circuit, decreasing the size
of the circuit and its complexity. Moreover, we established two detached transceivers.
The hardware components used in our design are in both first and second phases listed as
following:
3.1 Phase One
For the transmitter:
1.
2.
3.
4.
5.
BC547 Transistor (14).
Fixed and variable resistors.
Diode.
LED 1 watt.
Voltage source.
For the receiver:
1.
2.
3.
Frequency to voltage convertor circuit TC9400 (15).
Fixed and variable resistors.
TSL235R sensor (16).
3.2 Phase Two
Our circuit in the first phase faced many problems; the transmitter side hasn’t been
changed, but in the receiver side the TC9400 (15) frequency to voltage convertor was
slow, complex and gave a low bit rate up to 300 Bps so, it was urgent to replace the
TC9400 (15) by more efficient demodulation circuit.
So, we have replaced the receiver circuit with a much simpler, cheaper, higher bit rate (up
to 2.4kBps), higher speed and lower power consumption.
The receiver circuit in this phase consist of the following components:
1.
2.
3.
4.
TSL235R sensor (16).
Fixed and variable resistors.
BC547 Transistor (14).
AD790 comparator(17).
10 | P a g e
CHAPTER 4: Implementation
4.1 Time Table:
4.1.1 Phase one
Table 2 below shows our workflow during the first semester:
Week #
1,2,3
Objective
Comment
Simulation, electronic circuit, voltage
supply, used RGB LED
Transmitter design
Transmitter
implementation
4,5
6,7,8
Constructing the hardware circuit
Receiver design
9,10,11
Receiver implementation
12,13,14
System modification
Electronic circuit, sensor to be used,
voltage supply, try to solve frequency to
voltage problem
Constructing the hardware circuit, testing
distance
Usage of 1 Watt LED, increase voltage
levels, usage of a comparator to enhance
the demodulated signal
Table 2 Time Table of phase1
4.1.2 Phase two
Table 3 below shows our workflow during the second semester:
Week #
Objective
1,2,3,4,5,6 Receiver design
7,8,9,10
Receiver implementation
Comment
FSK demodulation circuit design
Constructing the hardware circuit, tuning,
calculations and solving problems
11,12
Server programming
Use Java programming language to
implement a server
13,14
Client programming
Use Java programming language to
implement a client
Table 3 Time Table of phase2
11 | P a g e
4.2 BLOCK DIAGRAM and ELECTRIC CIRCUITRY
4.2.1 Phase one
4.2.1.a The Transmitter:
Our design for the transmitter can be expressed in Figure 10 below that the data
source pushes the bits to be transmitted into an electronic circuit which provides two
output voltage levels depending on the bits(logic 1 or logic 0), then it is passed to the
LED to be modulated as light-intensity modulated signal.
Taking a closer look to the electronic circuit block; this circuit gives two output
voltage levels to maintain lighting function for the LED.
The concept behind this circuit is simply a transistor working as an On/Off circuit.
In figure 11, the data is passed from the data source module to the base of the transistor,
if it is logic 1, the current flows from collector to emitter with almost 9V DC causing the
diode to be reverse biased since the voltage at the anode is lower than the one at the
cathode, thus the LED intensity is high.
For logic 0, the transistor is off, thus the voltage at the cathode is 0V while it is
about 7V DC at the anode, causing the current flowing from the anode of the diode to the
LED with intensity lower than the previous case.
For no data transmission, the circuit acts as logic 0, and thus the LED is used only
for lighting.
Data Source
Module
Electronic
Circuit
LED
Figure 10 Transmitter Block Diagram
12 | P a g e
Figure 11 schematic of the transmitter
13 | P a g e
Figure 12 shows the transmitter circuit:
Figure 12 Actual photo of the Tx
4.2.1.b The Receiver:
For the Receiver, figure 13 shows the block diagram for our design of the receiver;
the sensor used in this circuit is TSL235R which is a light-to-frequency converter with a
high resolution conversion of light intensity to frequency, very low nonlinearity and low
supply voltage (2.7V) (16).
The TSL235R converts the light intensity to a square wave with a frequency varies
with light intensity.
The Figure 14 shows the functional block diagram for the TSL235R, it uses a
photodiode to detect the light and transfer it as current to the current-to-frequency
converter which translates it to frequency. Figure 15 shows the output signal from the
sensor appeared on the oscilloscope.
14 | P a g e
Light
TSL235R
TC9400
Comparator
(OpAmp)
Output
Figure 13 Receiver Block Diagram
Figure 14 Functional Block Diagram of the TSL235R
Figure 15 output signal from the sensor
The signal from the sensor is passed to a circuit that converts the frequency to a
corresponding voltage called TC9400.
The TC9400 is a multifunction IC that can convert the frequency to voltage (F/V)
and voltage to frequency (V/F) and has a lot of application such like 13-bit ADC, FM
Demodulation, PLL and more (15).
Figure 16 below shows the circuitry used for operating the TC9400 as F/V
converter (15).The Figures (17, 18, 19) show the output signal on pins 6 and 12 appeared
on the oscilloscope for different ASCII symbols.
15 | P a g e
As shown in figures (17, 18, 19), the output signal suffers from some noise
appears on the voltage levels, and it may be due to soldering method, or maybe a
capacitance effect. However, to get rid of such noise, the signal is passed through the
comparator with a reference voltage carefully compensated to recover the signal with no
noise, and thus it can be passed to the receiving port.
Figure 16 TC9400 as F/V converter with single supply
16 | P a g e
Figure 17 Transmitted and received ASCII (a)
Figure 18 Transmitted and received ASCII (a)
Figure 19 Transmitted and received ASCII (;)
17 | P a g e
The Figure 20 shows the receiver circuit:
Figure 20 Receiver circuit
18 | P a g e
4.2.2 Phase two
The transmitter circuit has no changes except a decrease in the driving power since
the operational voltage became 5V instead of 9V.
Figure 21 shows the schematic for our transmitter:
Figure 21 Transmitter schematic
Regarding to the receiver, the circuit has changed a lot; the used TSL235R(16) sensor still
the same as before but the TC9400(15) Frequency to voltage convertor circuit was slow
and has many problems so, we replace it by faster and more efficient components.
The Figure 22 shows the block diagram for the new receiver design:
Light
TSL235R
FSK
demodulator
Output
Figure 22 Receiver Block Diagram
19 | P a g e
The schematic of the receiver was as shown in the figure below:
Figure 23 Receiver schematic
Figure 24 shows the transmitted signal from the third Pin of the DB9:
Figure 24 Transmitted signal
20 | P a g e
Figure 25 shows the output signal from the sensor:
Figure 25 The output signal from the sensor
Figure 26 represents the first stage demodulation; the first capacitor demodulated the 1 as
shown:
Figure 26 The first step demodulated signal
21 | P a g e
Figure 27 represents the demodulated signal (after the comparator and the inverter):
Figure 27 Demodulated signal
The whole transceiver schematic was as shown in Figure 28 below:
Figure 28 Whole transceiver scematic
22 | P a g e
Figure 29 shows the whole transceiver circuit:
Figure 29 Transceiver circuit
After we demodulated the signal and in order to test our results, we wrote a Java
code (see appendix I) to send data then we received the same data on the hyper terminal at a
data rate equals to 2.4kBps and a maximum distance of 30cm with no errors. Figure 30
shows our results:
Figure 30 Testing the results
23 | P a g e
4.3 INTERNET CONNECTION
We wrote a Java code that creates an interaction between LIFI system and HTTP
protocol used for internet surfing; the code aims to enable the PC to act as a server (see
APPENDIX II) at the LIFI system side and a client (see APPENDIX III) on the internet direction.
In the client side, we designed a GUI to send the URL request then the server takes the
URL from the LIFI module and passes it through the internet and gets the HTML code,
then the code is transmitted over LIFI and stored as an internet page at the client side.
To make sure that the URL request is sent correctly; we added preamble and
trailer sequences at the beginning and the end of the URL at the client side then send it to
the server which checks if the sequence is true then it extracts the URL. After the
extraction, the server checks if the URL is correctly formed then it sends the HTML
code to the client. If not, it returns an invalid message box and notifies the user of an
invalid address. Finally, the client uses a check code to check the HTML then extract it
and return it as a web page.
24 | P a g e
CHAPTER5: Discussion and Conclusion
5.1 Evidence
In the first semester, we succeeded in implementing Tx and Rx circuits, and
sending ASCII data serially using the hyper Terminal over a distance of 20cm, with
voltage levels of 2V for logic0 and 2.5V for logic1 and receiving it effectively using the
circuit discussed in Chapter4.
Despite that, this test case was indoor case, and it doesn’t suffer from daylight
effect and other sources of lights around except the indoor lighting source (Florescent).
For the second phase of this project, we develop our system so it can reach more
than 30cm using only a small LED with no reception errors , also we pan out in
decreasing the complexity of the receiver with faster transmission and higher bit rate over
2.4kBps. Moreover, the cost of the circuit is decreased, the operating power is decreased
(use operation voltage equals to 5V instead of 9V) and the size became much more
smaller than before. Finally we succeeded in implementing two transceivers to be able to
transmit and receive simultaneously.
5.2 budget and Feasibility
When we succeeded in implementing the Tx, Rx circuits in the previous semester,
and because we put the cost efficiency into consideration, our project costs no more than
30$, and it is stated in the table below:
Component
TSL235R
TC9400
DB9
Batteries
1-Watt LED
Resistors, Capacitors, Diodes,…etc
Total Cost
Price
4.7$
10$
1.3$
3.5$
0.5$
10$
30$
Table 4 Tx, Rx Budget
25 | P a g e
But in the second part of the project we worked to develop a more robust system
with smaller size and faster with a cost does not reach half the cost of the circuit before.
Also we build two transceivers instead of detached transmitter and receiver. So, the total
cost of the whole transceiver became as we state:
Component
TSL235R
Demodulator
DB9
Transistors
1-Watt LED
Resistors, Capacitors, Diodes,…etc
Total Cost
Price
4.7$
1.5$
1.3$
1.5$
0.5$
2.5$
12$
Table 5 Transceiver Budget
5.3 Recommendations and Future Work
In future, we recommend to improve the following points:

Using software to figure out an interface for mobiles.

Inspecting handover and other mobility problems.

Doing a multi-users interconnection.

Increasing the distance between the two transceivers by increasing
transmission power or increasing number of LEDs.
26 | P a g e
REFRENCES
1. Hayt, W.H & Buck, J.A .(2005). Engineering Electromagnetics. 7th edition. p.
2. M.Tech (CSE) Student. (2014). Light Fidelity (LI-FI)-A Comprehensive Study.
International Journal of Computer Science and Mobile Computing. p.475
3. Jakhar, V. (2014). Li-Fi technology. March 08, 2014.
http://www.slideshare.net/kaushikchakrabarti31/lifi-report
4. Haas, H. (2012). Pure Li-Fi. http://purelifi.com/what_is_li-fi/li-fi-features/
5. Hass, H. (2014). Li-Fi research. http://www.see.ed.ac.uk/drupal/hxh
6. Povey, G. (2011). Visible light communications. September 20,2011.
http://visiblelightcomm.com/d-light-project-hits-target/
7. Haas, H. (2012). Pure Li-Fi. http://purelifi.com/what_is_li-fi/how-does-vlc-work/
8. Samsung/ETRI. (2009). IEEE 802.15 VLC PHY/MAC proposal- Samsung/ETRI. p.7
9. Samsung/ETRI. (2009). IEEE 802.15 VLC PHY/MAC proposal- Samsung/ETRI. p.20
10. Samsung/ETRI. (2009). IEEE 802.15 VLC PHY/MAC proposal- Samsung/ETRI. p.35
11. Samsung/ETRI. (2009). IEEE 802.15 VLC PHY/MAC proposal- Samsung/ETRI.
p.35-37
12. Samsung/ETRI. (2009). IEEE 802.15 VLC PHY/MAC proposal- Samsung/ETRI.
p.37
13. Samsung/ETRI. (2009). IEEE 802.15 VLC PHY/MAC proposal- Samsung/ETRI.
p.38-40
14. Fairchild. BC546/547/548/549/550.
http://datasheet.seekic.com/datasheet/Fairchild_Semiconductor_BC547.html
15. Microchip. Voltage-to-frequency/ frequency-to-voltage converter.
http://www.dz863.com/datasheet-828036163-TC9400_Voltage-to-frequencyFrequency-to-voltage-Converters/
16. TAOS. TSL235R Light-to-frequency converter. http://pdf1.alldatasheet.com/datasheetpdf/view/203012/TAOS/TSL235R.html
17. Fast, Precision comparator. AD790. http://html.alldatasheet.com/htmlpdf/48360/AD/AD790/19/1/AD790.html
27 | P a g e
APPENDIX I
package serial;
import gnu.io.*;
import java.io.*;
public class usb_send{
public class SerialPortHandler
{
private SerialPort serialPort;
private OutputStream outStream;
private InputStream inStream;
public void connect(String portName) throws IOException, PortInUseException, NoSuchPortException {
try {
// Obtain a CommPortIdentifier object for the port you want to open
CommPortIdentifier portId =CommPortIdentifier.getPortIdentifier(portName);
// Get the port's ownership
serialPort =(SerialPort) portId.open("Demo application", 5000);
// Set the parameters of the connection.
setSerialPortParameters();
// Open the input and output streams for the connection. If they won't
// open, close the port before throwing an exception.
outStream = serialPort.getOutputStream();
inStream = serialPort.getInputStream();
} catch (NoSuchPortException e) {
throw new IOException(e.getMessage());
} catch (PortInUseException e) {
throw new IOException(e.getMessage());
} catch (IOException e) {
28 | P a g e
serialPort.close();
throw e;
}
}
/**
* Get the serial port input stream
* @return The serial port input stream
*/
public InputStream getSerialInputStream() {
return inStream;
}
/**
* Get the serial port output stream
* @return The serial port output stream
*/
public OutputStream getSerialOutputStream() {
return outStream;
}
private void setSerialPortParameters() throws IOException {
int baudRate = 2400;
try {
serialPort.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_NONE);
29 | P a g e
} catch (UnsupportedCommOperationException ex) {
throw new IOException("Unsupported serial port parameter");
}
}
}
@SuppressWarnings("null")
public static void main(String[] args) {
usb_send x = new usb_send();
usb_send.SerialPortHandler ss = x.new SerialPortHandler();
String data_read;
String s= "We did it ;) ";
byte[] buffer = null ;
try{
for(;;){
ss.connect("COM5");
InputStream serialIn=ss.getSerialInputStream();
serialIn.read(buffer, 0, 0);
data_read=buffer.toString();
System.out.printf(data_read);
OutputStream serialOut = ss.getSerialOutputStream();
serialOut.write(s.getBytes());
serialOut.flush();
ss.serialPort.close();
}}
catch(Exception ex){
}}}
30 | P a g e
APPENDIX II
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import
import
import
import
import
import
import
import
import
import
import
import
import
java.awt.FlowLayout;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.io.BufferedReader;
java.io.IOException;
java.io.InputStream;
java.io.InputStreamReader;
java.io.OutputStream;
java.net.HttpURLConnection;
java.net.URL;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JOptionPane;
enum EventType {
CLOSE, Connect
};
class MyFrame extends JFrame {
public MyFrame() {
initializeComponents();
setSize(WIDTH, HEIGHT);
setTitle("LiFi Server");
setVisible(true);
setLocation(500, 300);
}
void initializeComponents() {
setLayout(new FlowLayout());
// Connect button
btnConnect = new JButton("Connect");
btnConnect.addActionListener(new myListener(EventType.Connect));
add(btnConnect);
// close button
btnClose = new JButton("Close");
btnClose.addActionListener(new myListener(EventType.CLOSE));
add(btnClose);
// message
JOptionPane.showMessageDialog(null,
"Designed by:Loai Bitawi & Madlin Najjar");
}
JButton btnClose;
JButton btnConnect;
final int WIDTH = 300;
final int HEIGHT = 100;
}
31 | P a g e
class myListener implements ActionListener {
EventType action;
public myListener(EventType action) {
this.action = action;
}
public void actionPerformed(ActionEvent event) // function in interface
{
switch (action) {
case Connect:
try {
TwoWaySerialComm x = new TwoWaySerialComm();
x.connect("COM5");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "no com port");
e.printStackTrace();
}
break;
case CLOSE:
System.exit(0);
}
}
}
public class TwoWaySerialComm {
CommPortIdentifier portIdentifier;
CommPort commPort;
SerialPort serialPort;
public TwoWaySerialComm() {
super();
}
boolean check_url(String url) {
String w = "http://www.";
if (url.contains(w) == true)
return true;
else
return false;
}
String correct_url(String req) {
String corrected;
int s, e;
s = req.indexOf("1010", 0);
e = req.indexOf("1100", s);
corrected = req.substring(s + 4, e);
return corrected;
}
void connect(String portName) throws Exception {
portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
32 | P a g e
} else {
commPort = portIdentifier.open(this.getClass().getName(), 2000);
if (commPort instanceof SerialPort) {
serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(2400,
SerialPort.DATABITS_8,SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
writer wr = new writer(out);
Thread write = new Thread(wr);
sendGet SG = new sendGet(in, wr);
Thread sender = new Thread(SG);
sender.start();
} else {
System.out.println("Error: Only serial ports are
handled");
}
}
}
/***************************** */
class sendGet implements Runnable {
boolean check = true;
String req, c = " ";
char ends;
InputStream in;
String USER_AGENT = "Mozilla/5.0";
String url_final;
String HTML = "";
writer wr;
public sendGet(InputStream in, writer wr) {
this.in = in;
this.wr = wr;
}
public void run() {
byte[] buffer;
int len = -1;
while (true) {
buffer = new byte[1024];
try {
while ((len = this.in.read(buffer)) > -1) {
// req="1010http://www.google.com1100";
req = new String(buffer, 0, len);
if (req.contains("1010") &&
req.contains("1100")) {
url_final = correct_url(req);
break;
} else {
continue;
}
}
check = check_url(url_final);
if (check == false) {
33 | P a g e
JOptionPane.showMessageDialog(null, "Invalid
URL");
HTML = "Invalid URL";
} else {
URL obj = new URL(url_final);
HttpURLConnection con = (HttpURLConnection)
obj
.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent",
USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request
to URL : "
+ url_final);
System.out.println("Response Code : " +
responseCode);
BufferedReader in = new BufferedReader(
new
InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
HTML = response.toString();
}
response = null;
}
wr.HTML = HTML;
Thread write = new Thread(wr);
write.start();
in.close();
req = "";
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class writer implements Runnable {
sendGet SG;
public String HTML = "";
OutputStream out;
public writer(OutputStream out) {
this.out = out;
}
public void run() {
try {
byte[] Buffer = HTML.getBytes();
int c = Buffer.length;
while (c > 0) {
this.out.write(Buffer);
34 | P a g e
this.out.flush();
}
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new MyFrame();
}
}
35 | P a g e
APPENDIX III
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
gnu.io.CommPort;
gnu.io.CommPortIdentifier;
gnu.io.SerialPort;
java.awt.FlowLayout;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.io.IOException;
java.io.InputStream;
java.io.OutputStream;
java.io.PrintWriter;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JOptionPane;
javax.swing.JTextField;
enum EventType {
CLOSE, Send, url_text
};
class MyFrame extends JFrame {
public MyFrame() {
initializeComponents();
setSize(WIDTH, HEIGHT);
setTitle("LiFi Client");
setVisible(true);
setLocation(500, 300);
}
public void initializeComponents() {
setLayout(new FlowLayout());
// Connect button
url_label = new JLabel("URL:");
add(url_label);
URL_field = new JTextField(20);
URL_field.setText("http://www.");
add(URL_field);
btnSend = new JButton("Send");
btnSend.addActionListener(new myListener(EventType.Send));
add(btnSend);
// close button
btnClose = new JButton("Close");
btnClose.addActionListener(new myListener(EventType.CLOSE));
add(btnClose);
// message
JOptionPane.showMessageDialog(null,
"Designed by:Loai Bitawi & Madlin Najjar");
}
JLabel url_label;
JButton btnClose;
JButton btnSend;
36 | P a g e
JTextField URL_field;
final int WIDTH = 300;
final int HEIGHT = 100;
public static String URL_Text;
class myListener implements ActionListener {
EventType action;
public myListener(EventType action) {
this.action = action;
}
public void actionPerformed(ActionEvent event) // function in interface
{
String url_request = "";
switch (action) {
case Send:
url_request = URL_field.getText();
try {
new TwoWaySerialComm().connect("COM5", url_request);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "no com port");
// TODO Auto-generated catch block
}
break;
case CLOSE:
System.exit(0);
}
}
}
}
public class TwoWaySerialComm {
public static boolean flag_req = true;
String correct_HTML(String HTML_code) {
String corrected;
int s, e;
s = HTML_code.indexOf("<!doctype html>", 0);
e = HTML_code.indexOf("</body></html>", s);
corrected = HTML_code.substring(s, e);
return corrected;
}
public TwoWaySerialComm() {
super();
}
void connect(String portName, String URL_add) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier
.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
37 | P a g e
CommPort commPort =
portIdentifier.open(this.getClass().getName(),
2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(2400,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
(new Thread(new SerialReader(in))).start();
System.out.println("Serial Reader Loaded");
(new Thread(new SerialWriter(out, URL_add))).start();
System.out.println("Serial Writer Loaded");
} else {
System.out.println("Error: Only serial ports are
handled");
}
}
}
/***************************** */
public class SerialReader implements Runnable {
InputStream in;
String HTML_code = "";
String HTML_final;
public SerialReader(InputStream in) {
this.in = in;
}
public void run() {
byte[] buffer = new byte[1024];
int len = -1;
try {
while (true) {
while ((len = this.in.read(buffer)) > -1) {
HTML_code = new String(buffer, 0, len);
if (HTML_code.contains("<!doctype html>")
&&
HTML_code.contains("</body></html>")) {
HTML_final = correct_HTML(HTML_code);
System.out.println(HTML_final);
break;
} else if (HTML_code.contains("Invalid URL"))
{
JOptionPane.showMessageDialog(null,
"Invalid URL, please
restart the program");
System.exit(0);
} else {
System.out.println(HTML_code);
continue;
}
38 | P a g e
}
PrintWriter out = new PrintWriter("Page.html");
out.println(HTML_final);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static class SerialWriter implements Runnable {
OutputStream out;
String url_add;
String s = "1010", e = "1100", url_final;
public SerialWriter(OutputStream out, String url_add) {
this.out = out;
this.url_add = url_add;
url_final = s + url_add + e;
}
public void run() {
byte[] Buffer = url_final.getBytes();
try {
int c = Buffer.length;
while (c > 0) {
this.out.write(Buffer);
this.out.flush();
System.out.println(url_final);
c = 0;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyFrame x = new MyFrame();
}
}
39 | P a g e
Download