0% found this document useful (0 votes)
4 views25 pages

Vishal MC EXP 02 TO 10 Without8

The document outlines the development of an Android application by Vishal Murugiah that includes multiple functionalities such as sending notifications, modifying GUI components, drawing graphical primitives, and managing a database. Each section provides XML layout and Java code for the respective functionalities, demonstrating the use of various Android components. The application allows users to interact with messages, change text properties, draw shapes, and perform CRUD operations on student data.

Uploaded by

harshspam29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views25 pages

Vishal MC EXP 02 TO 10 Without8

The document outlines the development of an Android application by Vishal Murugiah that includes multiple functionalities such as sending notifications, modifying GUI components, drawing graphical primitives, and managing a database. Each section provides XML layout and Java code for the respective functionalities, demonstrating the use of various Android components. The application allows users to interact with messages, change text properties, draw shapes, and perform CRUD operations on student data.

Uploaded by

harshspam29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

/*******************************************************************************************

NAME: Vishal Murugiah CLASS: TE-CMPN-02 BATCH:C6 ROLL NO: 53


AIM: Implement an application that creates an alert upon receiving a message. (EXP-02)
*******************************************************************************************/
Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_margin="10dp" android:orientation="vertical">

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"


android:text="Message" android:textSize="30sp" />

<EditText android:id="@+id/editText" android:layout_width="match_parent"


android:layout_height="wrap_content" android:singleLine="true"

android:textSize="30sp" />

<Button android:id="@+id/button" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_margin="30dp" android:layout_gravity="center"
android:text="Notify" android:textSize="30sp"/> </LinearLayout>

MainActivity.java:
package com.example.myapplication;

import android.app.Notification; import


android.app.NotificationChannel; import
android.app.NotificationManager; import
android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat; import
androidx.core.app.NotificationManagerCompat;
import android.view.View; import
android.widget.Button;
import android.widget.EditText;

import com.example.myapplication.R;
import com.example.myapplication.SecondActivity;

public class MainActivity extends AppCompatActivity {


Button notify;
EditText e; private static final String CHANNEL_ID =
"notification_channel";

@Override protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notify = findViewById(R.id.button); e
= findViewById(R.id.editText);
// Create Notification Channel (Required for Android 8.0+) createNotificationChannel();
notify.setOnClickListener(new View.OnClickListener() {
@Override public
void onClick(View v) {
sendNotification();
}
});
}
private void sendNotification() {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity( MainActivity.this,
0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this,

CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("New Message") .setContentText(e.getText().toString())
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(true);

NotificationManagerCompat manager = NotificationManagerCompat.from(this); manager.notify(1,


builder.build());
}

private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {


CharSequence name = "Notification Channel";
String description = "Channel for notifications"; int
importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);

NotificationManager notificationManager = getSystemService(NotificationManager.class);


if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);

}
}
}
}

SecondActivity.java: package
com.example.myapplication;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class SecondActivity extends AppCompatActivity


{
@Override protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_second);
}
}

OUTPUT:
/*******************************************************************************************
NAME: Vishal Murugiah CLASS: TE-CMPN-02 BATCH:C6 ROLL NO: 53
AIM: Develop an application that uses GUI components. (EXP-03)
*******************************************************************************************/
Activity_main.xml: -

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"
android:layout_width="match_parent" android:layout_height="match_parent">

<TextView android:id="@+id/textView" android:layout_width="match_parent"


android:layout_height="wrap_content" android:layout_margin="30dp" android:gravity="center"
android:text="WhatsUp!!" android:textSize="25sp" android:textStyle="bold" />

<Button android:id="@+id/button1" android:layout_width="match_parent"


android:layout_height="wrap_content" android:layout_margin="20dp" android:gravity="center"

android:text="Change font size" android:textSize="25sp" />


<Button android:id="@+id/button2" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_margin="20dp" android:gravity="center"
android:text="Change color" android:textSize="25sp" /> </LinearLayout>

MainAcitvity.java: -
package com.example.myapplication;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View; import
android.widget.Button; import
android.widget.TextView; public class MainActivity
extends AppCompatActivity {

private int ch = 1;
private float font = 30f;

@Override protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final TextView t = findViewById(R.id.textView);


Button b1 = findViewById(R.id.button1);
Button b2 = findViewById(R.id.button2);

b1.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
t.setTextSize(font);
font += 5;
if (font >= 50) font = 30; // Fix the reset logic
}
});

b2.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
int[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.CYAN, Color.YELLOW, Color.MAGENTA};
t.setTextColor(colors[ch % colors.length]);
ch++;
}
});
}
}

Output:-
/*******************************************************************************************
NAME: Vishal Murugiah CLASS: TE-CMPN-02 BATCH:C6 ROLL NO: 53
AIM: To make an application that draws basic graphical primitives on the screen. (EXP-04)
*******************************************************************************************/
Activity_main.xml: -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView" />
</RelativeLayout>

MainActiviyt.java: - package
com.example.myapplication;
import android.app.Activity;
import android.graphics.Bitmap; import
android.graphics.Canvas; import
android.graphics.Color; import
android.graphics.Paint; import
android.graphics.drawable.BitmapDrawable;
import android.os.Bundle; import
android.widget.ImageView; public class MainActivity
extends AppCompatActivity {

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);


setContentView(R.layout.activity_main);

// Creating a Bitmap
Bitmap bg = Bitmap.createBitmap(720, 1280, Bitmap.Config.ARGB_8888);

// Setting the Bitmap as background for the ImageView


ImageView i = findViewById(R.id.imageView);
i.setBackground(new BitmapDrawable(getResources(), bg));

// Creating the Canvas Object


Canvas canvas = new Canvas(bg);

// Creating the Paint Object and setting its color & TextSize
Paint paint = new Paint(); paint.setColor(Color.BLUE);
paint.setTextSize(50);

// Drawing a Rectangle
canvas.drawText("Rectangle", 420, 150,
paint); canvas.drawRect(400, 200, 650, 700,
paint);

// Drawing a Circle
canvas.drawText("Circle", 120, 150, paint);
canvas.drawCircle(200, 350, 150, paint);

// Drawing a Square
canvas.drawText("Square", 120, 800, paint);
canvas.drawRect(50, 850, 350, 1150, paint);

// Drawing a Line canvas.drawText("Line",


480, 800, paint);
canvas.drawLine(520, 850, 520, 1150, paint);
}
}

OUTPUT:
/*******************************************************************************************
NAME: Vishal Murugiah CLASS: TE-CMPN-02 BATCH:C6 ROLL NO: 53
AIM: Develop an application that makes use of database. (EXP-05)
*******************************************************************************************/
Activity_main.xml: -
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"


android:layout_x="50dp" android:layout_y="20dp" android:text="Student Details"
android:textSize="30sp" />

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"


android:layout_x="20dp" android:layout_y="110dp" android:text="Enter Rollno:"
android:textSize="20sp" />

<EditText
android:id="@+id/Rollno"
android:inputType="text"
android:textSize="20sp" />
<EditText android:id="@+id/Marks"
android:layout_width="150dp"
android:layout_height="wrap_content
" android:layout_x="175dp"
android:layout_y="200dp"
android:inputType="number"
android:textSize="20sp" />
<Button android:id="@+id/Insert"
android:layout_width="150dp"
android:layout_height="wrap_content
" android:layout_x="25dp"
android:layout_y="300dp"
android:text="Insert"
android:textSize="30dp" />
<Button android:id="@+id/Delete" android:layout_width="150dp"
android:layout_x="200dp" android:layout_y="300dp"
android:text="Delete" android:textSize="30dp" />

<Button
android:id="@+id/Update"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="400dp"
android:text="Update"
android:textSize="30dp" />

<Button android:id="@+id/View" android:layout_width="150dp"


android:layout_height="wrap_content" android:layout_x="200dp" android:layout_y="400dp"
android:text="View" android:textSize="30dp" />
android:layout_x="100dp"
android:layout_y="500dp"
android:text="View All"
android:textSize="30dp"
/>

</AbsoluteLayout>

MainActivity.java package
com.example.exno5;

import android.content.ContentValues; import


android.content.Context; import
android.database.Cursor; import
android.database.sqlite.SQLiteDatabase; import
android.database.sqlite.SQLiteOpenHelper; import
android.os.Bundle; import android.view.View;
import android.widget.Button;
import android.widget.EditText; import
androidx.appcompat.app.AlertDialog; import
androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


EditText rollno, name, marks;
Button insert, delete, update, view, viewAll;

DatabaseHelper dbHelper;

@Override protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rollno = findViewById(R.id.Rollno); name
= findViewById(R.id.Name);
marks = findViewById(R.id.Marks); insert =
findViewById(R.id.Insert); delete =
findViewById(R.id.Delete); update =
findViewById(R.id.Update); view =
findViewById(R.id.View); viewAll =
findViewById(R.id.ViewAll); dbHelper =
new DatabaseHelper(this);

insert.setOnClickListener(view -> insertData());


delete.setOnClickListener(view -> deleteData()); update.setOnClickListener(view
-> updateData());
view.setOnClickListener(view -> viewData());
viewAll.setOnClickListener(view -> viewAllData());
}
private void insertData() {
if (rollno.getText().toString().trim().isEmpty() || name.getText().toString().trim().isEmpty() ||
marks.getText().toString().trim().isEmpty()) {
showMessage("Error", "Please enter all values"); return;
}
boolean isInserted = dbHelper.insertStudent(rollno.getText().toString(), name.getText().toString(),
marks.getText().toString());
showMessage("Success", isInserted ? "Record added" : "Insertion failed"); clearText();
}
private void deleteData() { if
(rollno.getText().toString().trim().isEmpty()) {
showMessage("Error", "Please enter Rollno");
return;
}
boolean isDeleted = dbHelper.deleteStudent(rollno.getText().toString());
showMessage("Success", isDeleted ? "Record Deleted" : "Invalid Rollno"); clearText();
}

private void updateData() {


if (rollno.getText().toString().trim().isEmpty()) {
showMessage("Error", "Please enter Rollno"); return;
}
boolean isUpdated = dbHelper.updateStudent(rollno.getText().toString(), name.getText().toString(),
marks.getText().toString());
showMessage("Success", isUpdated ? "Record Modified" : "Invalid Rollno"); clearText();
}

private void viewData() {


if (rollno.getText().toString().trim().isEmpty()) {
showMessage("Error", "Please enter Rollno"); return;
}
Cursor c = dbHelper.getStudent(rollno.getText().toString());
if (c.moveToFirst()) {
name.setText(c.getString(1));
marks.setText(c.getString(2));
} else {
showMessage("Error", "Invalid Rollno");
clearText();
}
}

private void viewAllData() {


Cursor c = dbHelper.getAllStudents(); if
(c.getCount() == 0) {
showMessage("Error", "No records found"); return;
}
StringBuilder buffer = new StringBuilder(); while
(c.moveToNext()) {
buffer.append("Rollno: ").append(c.getString(0)).append("\n");
buffer.append("Name: ").append(c.getString(1)).append("\n"); buffer.append("Marks:
").append(c.getString(2)).append("\n\n"); }
showMessage("Student Details", buffer.toString());
}

private void showMessage(String title, String message) {


new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setCancelable(true)
.show();

private void clearText() {


rollno.setText("");
name.setText("");
marks.setText("");
rollno.requestFocus();
}
}

class DatabaseHelper extends SQLiteOpenHelper { private


static final String DATABASE_NAME = "StudentDB"; private
static final String TABLE_NAME = "student";

DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " +
TABLE_NAME + " (rollno TEXT PRIMARY KEY, name TEXT, marks TEXT)");
}

@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db);
}

boolean insertStudent(String rollno, String name, String marks) {


SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("rollno", rollno);
values.put("name", name);
values.put("marks", marks);
return db.insert(TABLE_NAME, null, values) != -1;
}

boolean deleteStudent(String rollno) {


SQLiteDatabase db = this.getWritableDatabase(); return
db.delete(TABLE_NAME, "rollno=?", new String[]{rollno}) > 0; }

boolean updateStudent(String rollno, String name, String marks) {


SQLiteDatabase db = this.getWritableDatabase(); ContentValues
values = new ContentValues(); values.put("name", name);
values.put("marks", marks);

return db.update(TABLE_NAME, values, "rollno=?", new String[]{rollno}) > 0;


}
Cursor getStudent(String rollno) {
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE rollno=?", new String[]{rollno});
}
Cursor getAllStudents() {
SQLiteDatabase db = this.getReadableDatabase(); return
db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
}
}
OUTPUT:
/*******************************************************************************************
NAME: Vishal Murugiah CLASS: TE-CMPN-02 BATCH: C6 ROLL NO: 53
AIM: To implement a basic function of Code Division Multiple Access. (EXP-06)
*******************************************************************************************/
Code: -
import numpy as np

# Define orthogonal spreading codes c1 = [1, 1, 1, 1] c2 = [1, -1, 1, -1] c3 = [1, 1, -1, -1] c4 = [1, -1, -1, 1]

# Get user input for data bits


print("Enter the data bits for each user:")
d1 = int(input("Enter D1 (0 or 1): ")) * 2 - 1
# Convert 0 to -1, 1 to 1 d2 = int(input("Enter D2 (0 or 1): ")) * 2 - 1 d3 = int(input("Enter D3 (0 or 1): ")) * 2 - 1 d4
= int(input("Enter D4 (0
or 1): ")) * 2 - 1

# Encode data using spreading codes


r1 = np.multiply(c1, d1) r2
= np.multiply(c2, d2) r3 =
np.multiply(c3, d3) r4 =
np.multiply(c4, d4)

# Combine all signals (superimposed signal in the channel)


resultant_channel = r1 + r2 + r3 + r4 print("Resultant
Channel:", resultant_channel)

# Select which user to listen to


channel = int(input("Enter the station to listen (1 for C1, 2 for C2, 3 for C3, 4 for C4): "))
# Assign the correct spreading code based on selection
if channel == 1: rc = c1
elif channel == 2: rc
= c2
elif channel == 3: rc
= c3
elif channel == 4: rc
= c4
else: print("Invalid channel selection.")
exit()
# Perform decoding (correlation)
inner_product = np.multiply(resultant_channel, rc)
print("Inner Product:", inner_product) #
Reconstruct the original data bit res1 =
sum(inner_product) data = res1 /
len(inner_product) print("Data bit that was sent:",
int(data))
OUTPUT:
/*******************************************************************************************
NAME: Vishal Murugiah CLASS: TE-CMPN-02 BATCH: C6 ROLL NO: 53
AIM: Implementation of GSM security algorithms (A3/A5/A8). (EXP-07)
******************************************************************************************
*/ import random import re import copy import sys

# A3 Algorithm for Authentication


def a3_algorithm(): k =
random.getrandbits(128) m =
random.getrandbits(128) kb =
bin(k)[2:].zfill(128)
# Convert key to binary mb
= bin(m)[2:].zfill(128)
# Convert message to binary

kbl = kb[:64]
kbr = kb[64:] mbl
= mb[:64] mbr =
mb[64:]

a1 = int(kbl, 2)
a2 = int(kbr, 2)

a3 = a1 ^ a2 # XOR operation
a4 = bin(a3)[2:].zfill(64)
# Convert back to binary
a5 = a4[:32]
a6 = a4[32:]

a7 = int(a5, 2)

print("\n--- A3 Algorithm ---")


print("128 Bit Key: ", kb)
print("128 Random Bits Generated: ", mb) print("RES/SRES:
", bin(a7)[2:].zfill(len(a5)))

# A8 Algorithm for Key Generation reg_x_length


= 19
reg_y_length = 22 reg_z_length
= 23

reg_x = [] reg_y
= [] reg_z = []
key_one = ""

def loading_registers(key):
global reg_x, reg_y, reg_z i,
j, k, r = 0, 0, 0, 0
reg_x = [int(key[i]) for i in
range(reg_x_length)] reg_y
= [int(key[i + reg_x_length])
for i in
range(reg_y_length)] reg_z
= [int(key[i + reg_x_length
+ reg_y_length]) for i in
range(reg_z_length)] def
set_key(key):
global key_one if len(key) == 64 and
re.match("^([01])+", key):
key_one = key loading_registers(key)
return True return
False

def get_keystream(length): reg_x_temp =


copy.deepcopy(reg_x) reg_y_temp =
copy.deepcopy(reg_y) reg_z_temp =
copy.deepcopy(reg_z) keystream = []

for _ in range(length):
majority = (reg_x_temp[8] + reg_y_temp[10] + reg_z_temp[10]) > 1

if reg_x_temp[8] == majority: new = reg_x_temp[13] ^ reg_x_temp[16] ^ reg_x_temp[17] ^


reg_x_temp[18] reg_x_temp = [new] + reg_x_temp[:-1]

if reg_y_temp[10] == majority: new_one = reg_y_temp[20] ^ reg_y_temp[21] reg_y_temp =


[new_one] + reg_y_temp[:-1]

if reg_z_temp[10] == majority: new_two = reg_z_temp[7] ^ reg_z_temp[20] ^ reg_z_temp[21] ^


reg_z_temp[22] reg_z_temp = [new_two] + reg_z_temp[:-1]

keystream.append(reg_x_temp[18] ^ reg_y_temp[21] ^ reg_z_temp[22])

return keystream def to_binary(plain): return ''.join(format(ord(c), '08b')

for c in plain)

def convert_binary_to_str(binary): return ''.join(chr(int(binary[i:i+8], 2)) for i in range(0, len(binary), 8))

def encrypt(plain): binary = to_binary(plain) keystream = get_keystream(len(binary)) return


''.join(str(int(binary[i]) ^ keystream[i]) for i in range(len(binary)))

def decrypt(cipher): keystream = get_keystream(len(cipher)) binary = ''.join(str(int(cipher[i]) ^ keystream[i]) for


i in range(len(cipher))) return convert_binary_to_str(binary)

def user_input_key(): while True:

key = input("Enter a 64-bit key: ") if len(key) == 64 and re.match("^([01])+", key):


return key print("Invalid key! Try again.")

def user_input_choice(): while True:


choice = input("[0]: Quit\n[1]: Encrypt\n[2]: Decrypt\nPress 0, 1, or 2: ")
if choice in ['0', '1', '2']:
return choice print("Invalid choice! Try again.")

def user_input_plaintext(): return input("Enter the plaintext: ") def


user_input_ciphertext(): while True:
cipher = input("Enter a ciphertext (binary format): ") if re.match("^([01])+", cipher):

return cipher print("Invalid ciphertext! Try again.") def main(): a3_algorithm() # Run

A3 Algorithm first key = user_input_key() set_key(key)

while True:
choice = user_input_choice() if choice == '0': print("Have an awesome day!") sys.exit(0) elif choice
== '1': plaintext = user_input_plaintext() print("Ciphertext:", encrypt(plaintext)) elif choice
== '2':
ciphertext = user_input_ciphertext() print("Decrypted text:",
decrypt(ciphertext)) # Run the main function if name == " main ": main()

OUTPUT:
/*******************************************************************************************
NAME: Vishal Murugiah CLASS: TE-CMPN-02 BATCH: C6 ROLL NO: 53
AIM: Illustration of Hidden Terminal Problem (NS-2). (EXP-9)
*******************************************************************************************/
Input:

BEGIN{
sim_end = 200; i=0;
while (i<=sim_end) {sec[i]=0; i+=1;};
}
{
if ($1=="r" && $7=="cbr"&& $3=="_0_") {sec[int($2)]+=$8; };
}
END{i=0;
while (i<=sim_end) {print i " " sec[i]; i+=1;};
}# Define options
set val(chan) Channel/WirelessChannel ;# channel type setval(prop) Propagation/FreeSpace ;# radio-propagation
modelset val(netif) Phy/WirelessPhy ;# network interface typeset val(mac) Mac/802_11 ;# MAC type
set val(ifq) Queue/DropTail/PriQueue ;# interface queuetype set val(ll) LL ;# link layer type set val(ant)
Antenna/OmniAntenna ;# antenna model set val(ifqlen) 10000 ;# max packet in ifq set val(nn) 5 ;#number of
mobilenodes
set val(rp) DSR ;# routing protocol
set val(x) 600 ;# X dimension of topography set val(y) 600
;# Y dimension of topography set val(stop) 100 ;# time ofsimulation end set val(R) 300 set
opt(tr) out.tr
set ns [new Simulator] set tracefd [open $opt(tr) w]set windowVsTime2 [open win.tr w] set namtrace [open
simwrls.nam w] Mac/802_11 set dataRate_ 1.2e6 Mac/802_11set RTSThreshold_ 100 $ns trace-all $tracefd #$ns
use- newtrace
$ns namtrace-all-wireless $namtrace $val(x) $val(y) # set up topography objectset topo [new Topography] $topo
load_flatgrid $val(x) $val(y) create-god $val(nn)

#
# Create nn mobilenodes [$val(nn)] and attach them tothe channel. # # configure the nodes $ns
node-config -adhocRouting $val(rp) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-channelType $val(chan) \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace ON \
-movementTrace ON Phy/WirelessPhy set CSThresh 30.5e-10 for
{set i 0} {$i < $val(nn) } { incr i } { setnode_($i) [$ns node] }
$node_(0) set X_ $val(R)
$node_(0) set Y_ $val(R)
$node_(0) set Z_ 0
$node_(1) set X_ $val(R)
$node_(1) set Y_ 0
$node_(1) set Z_ 0
$node_(2) set X_ 0
$node_(2) set Y_ $val(R)
$node_(2) set Z_ 0
$node_(3) set X_ [expr $val(R) *2]
$node_(3) set Y_ $val(R)
$node_(3) set Z_ 0
$node_(4) set X_ $val(R)
$node_(4) set Y_ [expr $val(R) *2]
$node_(4) set Z_ 0
for {set i 0} {$i<$val(nn)} {incr i} {
$ns initial_node_pos $node_($i) 30
}
# Generation of movements
$ns at 0 "$node_(1) setdest $val(R) $val(R) 3.0"
$ns at 0 "$node_(2) setdest $val(R) $val(R) 3.0"
$ns at 0 "$node_(3) setdest $val(R) $val(R) 3.0"
$ns at 0 "$node_(4) setdest $val(R) $val(R) 3.0"
# Set a TCP connection between node_(0) and node_(1) set tcp[new Agent/TCP/Newreno] #$tcp set class_ 2 set
tcp [new Agent/UDP]

$tcp set class_ 2


set sink [new Agent/Null] $ns
attach-agent $node_(1) $tcp
$ns attach-agent $node_(0) $sink
$ns connect $tcp $sink
set ftp [new Application/Traffic/CBR]
$ftp attach-agent $tcp
$ns at 0.0 "$ftp start"
# ################################################
# For coloring but doesnot work
# ################################################
$tcp set fid_ 1
$ns color 1 blue #///////////////////////////////////////////////// settcp [new Agent/UDP]
$tcp set class_ 2
set sink [new Agent/Null] $ns
attach-agent $node_(2) $tcp
$ns attach-agent $node_(0) $sink
$ns connect $tcp $sink
set ftp [new Application/Traffic/CBR]
$ftp attach-agent $tcp
$ns at 0.0 "$ftp start"set tcp [new Agent/UDP]
$tcp set class_ 2
set sink [new Agent/Null] $ns
attach-agent $node_(3) $tcp
$ns attach-agent $node_(0) $sink
$ns connect $tcp $sink
set ftp [new Application/Traffic/CBR]
$ftp attach-agent $tcp
$ns at 0.0 "$ftp start"set tcp [new Agent/UDP]
$tcp set class_ 2
set sink [new Agent/Null] $ns
attach-agent $node_(4) $tcp
$ns attach-agent $node_(0) $sink
$ns connect $tcp $sink
set ftp [new Application/Traffic/CBR]
$ftp attach-agent $tcp
$ns at 0.0 "$ftp start"
# Telling nodes when the simulation ends #for {set i 0} {$i
< $val(nn) } { incr i } { # $ns at $val(stop) "$node_($i)reset"; #}
# ending nam and the simulation
$ns at $val(stop) "$ns nam-end-wireless $val(stop)" $ns
at $val(stop) "stop"

$ns at $val(stop) "puts \"end simulation\" ; $ns halt"proc stop {} { exec awk -f fil.awk out.tr
> out.xgr exec xgraph out.xgr & global
ns tracefd namtrace
$ns flush-trace close $tracefd close $namtraceexec nam simwrls.nam &
}
$ns run

OUTPUT:
/*******************************************************************************************
NAME: Vishal Murugiah CLASS: TE-CMPN-02 BATCH: C6 ROLL NO: 53
AIM: To setup & configuration of Wireless Access Point (AP) using NS3. Analyze the Wi-Fi communication range in
the presence of the access point (AP) and the base station (BS). (EXP-10)
*******************************************************************************************/
INPUT:

#include "ns2/command-line.h"#include "ns2/config.h" #include "ns2/boolean.h" #include "ns2/string.h"


#include "ns2/yans-wifi-helper.h"#include "ns2/ssid.h"
#include "ns2/mobility-helper.h" #include "ns2/on-off- helper.h" #include "ns2/yans-wifi-channel.h" #include
"ns2/mobility-model.h" #include "ns2/packet-socket- helper.h"#include "ns2/packet-socket-address.h"#include
"ns2/athstats-helper.h"
using namespace ns2;
static bool g_verbose = true;void
DevTxTrace (std::string context, Ptr<const Packet> p)
{
if (g_verbose)
{
std::cout << " TX p: " << *p << std::endl;
} } void
DevRxTrace (std::string context, Ptr<const Packet> p)
{
if (g_verbose)
{
std::cout << " RX p: " << *p << std::endl;
} } void
PhyRxOkTrace (std::string context, Ptr<const Packet> packet, doublesnr, WifiMode mode, WifiPreamble preamble)
{ if (g_verbose) {

std::cout << "PHYRXOK mode=" << mode << " snr=" << snr << " " << *packet
<< std::endl;
} } void
PhyRxErrorTrace (std::string context, Ptr<const Packet> packet,double snr)
{
if (g_verbose)
{
std::cout << "PHYRXERROR snr=" << snr << " " << *packet <<std::endl;
} } void
PhyTxTrace (std::string context, Ptr<const Packet> packet, WifiModemode, WifiPreamble preamble, uint8_t
txPower)
{
if (g_verbose)
{
std::cout << "PHYTX mode=" << mode << " " << *packet << std::endl;
} } void
PhyStateTrace (std::string context, Time start, Time duration,WifiPhyState state)
{
if (g_verbose)
{
std::cout << " state=" << state << " start=" << start << "duration=" << duration << std::endl;
}
}
static void
SetPosition (Ptr<Node> node, Vector position)
{
Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();mobility->SetPosition (position);
}
static Vector
GetPosition (Ptr<Node> node)
{
Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();return mobility- >GetPosition
();
}
static void AdvancePosition (Ptr<Node> node)
{
Vector pos = GetPosition (node); pos.x += 5.0; if (pos.x >= 210.0)
{ return;
}
SetPosition (node, pos); Simulator::Schedule (Seconds (1.0), &AdvancePosition, node);
}
int main (int argc, char *argv[])

{
CommandLine cmd;
cmd.AddValue ("verbose", "Print trace information if true",g_verbose); cmd.Parse (argc, argv);
Packet::EnablePrinting ();
WifiHelper wifi; MobilityHelper mobility; NodeContainer stas; NodeContainer ap; NetDeviceContainer staDevs;
PacketSocketHelper packetSocket;stas.Create (2); ap.Create
(1);
// give packet socket powers to nodes. packetSocket.Install (stas);packetSocket.Install (ap); WifiMacHelper wifiMac;
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default (); YansWifiChannelHelper
wifiChannel = YansWifiChannelHelper::Default(); wifiPhy.SetChannel (wifiChannel.Create ()); Ssid ssid = Ssid ("wifi-
default"); wifi.SetRemoteStationManager ("ns3::ArfWifiManager"); // setup stas. wifiMac.SetType
("ns3::StaWifiMac", "ActiveProbing", BooleanValue(true), "Ssid", SsidValue (ssid)); staDevs = wifi.Install (wifiPhy,
wifiMac, stas); // setup ap. wifiMac.SetType ("ns3::ApWifiMac", "Ssid", SsidValue (ssid));wifi.Install (wifiPhy,
wifiMac, ap);
// mobility. mobility.Install (stas); mobility.Install (ap);
Simulator::Schedule (Seconds (1.0), &AdvancePosition, ap.Get (0));PacketSocketAddress socket;
socket.SetSingleDevice (staDevs.Get (0)->GetIfIndex ()); socket.SetPhysicalAddress (staDevs.Get (1)->GetAddress
());socket.SetProtocol (1);
OnOffHelper onoff ("ns3::PacketSocketFactory", Address (socket));onoff.SetConstantRate (DataRate
("500kb/s")); ApplicationContainer apps = onoff.Install (stas.Get (0)); apps.Start(Seconds (0.5)); apps.Stop
(Seconds (43.0)); Simulator::Stop (Seconds (44.0));
Config::Connect ("/NodeList/*/DeviceList/*/Mac/MacTx", MakeCallback(&DevTxTrace)); Config::Connect
("/NodeList/*/DeviceList/*/Mac/MacRx", MakeCallback(&DevRxTrace)); Config::Connect
("/NodeList/*/DeviceList/*/Phy/State/RxOk",MakeCallback (&PhyRxOkTrace));
Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/RxError",
MakeCallback (&PhyRxErrorTrace));
Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/Tx",MakeCallback (&PhyTxTrace));
Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/State",MakeCallback (&PhyStateTrace));
AthstatsHelper athstats; athstats.EnableAthstats ("athstats-sta", stas); athstats.EnableAthstats ("athstats-ap", ap);
Simulator::Run (); Simulator::Destroy ();return 0;
}
OUTPUT:

You might also like