Version=1.90
IconFile=
FullScreen=True
IncludeTitle=False
NumberOfModules=0
Package=b4a.smarthomeapp
Label=Smart home automation
VersionCode=1
VersionString=
Orientation=portrait
CanInstallToExternalStorage=True
DoNotOverwriteManifest=False
ManifestCode=
NumberOfFiles=14
File1=about.wav
File2=appliancecontrol.wav
File3=ding.wav
File4=door control.wav
File5=frontintro.bal
File6=help_appliances.wav
File7=help_door.wav
File8=help_sensomate.wav
File9=help_sensors.wav
File10=help_settings.wav
File11=sensomate.wav
File12=sensors.wav
File13=settings.wav
File14=welcome.wav
NumberOfLibraries=5
Library1=animation
Library2=core
Library3=dialogs
Library4=randomaccessfile
Library5=serial
@EndOfDesignText@
    'Activity module
Sub Process_Globals
	'These global variables will be declared once when the application starts.
	'These variables can be accessed from all modules.
	Dim mp As MediaPlayer		'for playing audio messages
	Dim serial1 As Serial		'for serial communication via bluetooth
	Dim astreams As AsyncStreams	'used in handling serial data
	Dim badmin As BluetoothAdmin	'for handling bluetooth adaptor
	Dim connected As Boolean		'depicts global serial connection status
	Dim sensors As String
	Dim s As String					'general purpose,for sending serial commands
	Dim sb As String			'used in fetching encoded serial data so received
	Dim fullrx As Boolean		'used in fetching encoded serial data so received
End Sub
Sub Globals
	'These global variables will be redeclared each time the activity is created.
	'These variables can only be accessed from this module.
	Dim numdial As NumberDialog
	Dim inpbox As InputDialog
	
	Dim t1 As Timer,t2 As Timer	'for animation
	Dim i As Int
	Dim animate1 As Animation,animate2 As Animation
	Dim panimate1 As Animation
	Dim ImageView1 As ImageView	'home
	Dim ImageView2 As ImageView	'mobile
	Dim Label1 As Label	'smartphone based
	Dim Label2 As Label	'home automation
	Dim Label3 As Label	'first dot
	Dim Label4 As Label	'second dot
	Dim Label5 As Label	'third dot
	Dim Label6 As Label
	Dim Labelfan As Label
	Dim Labellight1 As Label
	Dim Labellight2 As Label
	Dim Labeltelevision As Label
	Dim Panelappliances As Panel
	Dim Buttondoor As Button
	Dim Buttonsenfan As Button
	Dim Buttonsenlight1 As Button
	Dim Buttonsenlight2 As Button
	Dim Imageappliance As ImageView
	Dim Imagedoor As ImageView
	Dim Imagedoorstatus As ImageView
	Dim Imagesensomate As ImageView
	Dim Imagesensors As ImageView
	Dim Imagesettings As ImageView
	Dim Label10 As Label
	Dim Label11 As Label
	Dim Label12 As Label
	Dim Label13 As Label
	Dim Label14 As Label
	Dim Label15 As Label
	Dim Label16 As Label
	Dim Label17 As Label
	Dim Label18 As Label
	Dim Label7 As Label
	Dim Label8 As Label
	Dim Label9 As Label
	Dim Labeldoorstatus As Label
	Dim Labellightin As Label
	Dim Labellightout As Label
	Dim Labelmotion As Label
	Dim Labeltempin As Label
	Dim Labeltempout As Label
	Dim Paneldoor As Panel
	Dim Panelsensomate As Panel
	Dim Panelsensors As Panel
	Dim Panelsettings As Panel
	Dim Buttonsavelog As Button
	Dim Buttonbluetoothswitch As Button
	Dim ImageView3 As ImageView
	Dim Label19 As Label
	Dim Labelbluetoothstatus As Label
	Dim Buttonconnect As Button
	Dim Buttonsenmotion As Button
	Dim Label20 As Label
	Dim Buttonpassword As Button
	Dim Buttonalloff As Button
	Dim Buttonallon As Button
	Dim Buttonsleepmode As Button
	Dim Panelabout As Panel
	Dim Labellpg As Label
	Dim Buttonfanoff As Button
	Dim Buttonfanon As Button
	Dim Buttonlight1off As Button
	Dim Buttonlight1on As Button
	Dim Buttonlight2off As Button
	Dim Buttonlight2on As Button
	Dim Buttontvoff As Button
	Dim Buttontvon As Button
	Dim Buttonresetautoconnect As Button
	Dim Buttonsleepmodeoff As Button
	Dim ImageView4 As ImageView
	Dim ImageView5 As ImageView
	Dim ImageView6 As ImageView
	Dim ImageView7 As ImageView
	Dim Label21 As Label
	Dim Label22 As Label
	Dim Label23 As Label
	Dim Buttonprogfire As Button
End Sub
Sub Activity_Create(FirstTime As Boolean)
	Activity.LoadLayout("frontintro")	'load the layout file onto activity
	If FirstTime Then'process starts
		mp.Initialize	'initialize the media player
		badmin.Initialize("badmin")
		serial1.Initialize("Serial1") 
	End If
	
	connected=False
		
	'hide all the panels first to make main animation visible
	Panelappliances.Visible=False
	Panelsensors.Visible=False
	Panelsensomate.Visible=False
	Paneldoor.Visible=False
	Panelsettings.Visible=False
	Panelabout.Visible=False
	
	ImageView1.Visible=True	'enable the "HOME" image
	ImageView2.Visible=False	'disable the "MOBILE" image
	Label1.Visible=False
	Label2.Visible=False
	Label3.Visible=False
	Label4.Visible=False
	Label5.Visible=False
	i=0
	t1.Initialize("t1",700)
	t2.Initialize("t2",1500)	'delay between main animation and actual control panel
	t2.Enabled=False
	animate1.InitializeAlpha("animate1",0,1)'used in animating the main animation label
	animate1.Duration=1000
	animate2.InitializeAlpha("animate2",0,1)'used in animating the main animation label
	animate2.Duration=1000
	panimate1.InitializeAlpha("panimate1",0,1)'used in animating the different panels
	panimate1.Duration=1000
	
	'add menu items
	Activity.AddMenuItem("Appliances","mnuappliances")
	Activity.AddMenuItem("Sensors","mnusensors")
	Activity.AddMenuItem("Door control","mnudoor")
	Activity.AddMenuItem("Sensomate","mnusensomate")
	Activity.AddMenuItem("Settings","mnusettings")	
	Activity.AddMenuItem("About","mnuabout")
	
	'==================for sensor reading folder
	If File.IsDirectory(File.DirRootExternal,"smarthome")=False Then'check whether this folder already exists in the root directory
		File.MakeDir(File.DirRootExternal,"smarthome")'if not make a folder in the root directory of SD card for storing sensor readings 
	End If
	
	'==================for password file
	If File.Exists(File.DirInternal,"password.txt")=False Then	'if the text file "password.txt" containing password does not exists
		File.WriteString(File.DirInternal,"password.txt","45206734")	'the create it,with password="45206734"
	End If	
	
	If File.ReadString(File.DirInternal,"password.txt")<>"" Then 'password is enabled,something in the file
		inpbox.InputType=inpbox.INPUT_TYPE_TEXT
		inpbox.PasswordMode=True
		If inpbox.Show("","Enter login password :","OK","Cancel","",Null)=DialogResponse.POSITIVE Then 'request login password from user
			If inpbox.Input<>File.ReadString(File.DirInternal,"password.txt") Then'if password incorrect
				Msgbox("Incorrect password,try again!","Error")
				ExitApplication
			End If	
		Else 
			ExitApplication
		End If
	End If	
	
	'===================for host default address file
	If File.Exists(File.DirInternal,"mac.txt")=False Then	'if the text file "mac.txt" containing host default MAC address does not exists
		File.WriteString(File.DirInternal,"mac.txt","")	'the create it,with null data
	End If	
		
	disable_main_views			'disable all main buttons initially
	t1.Enabled=True				'start the animation
End Sub
Sub Activity_Resume
	If badmin.IsEnabled=False Then'if bluetooth is OFF
		If Msgbox2("This application requires bluetooth to be turned ON" & CRLF & "Turn it ON?","Error","Yes","NO","",Null)=DialogResponse.POSITIVE Then 'yes,turn it ON
			badmin.enable'turn ON bluetooth
		Else 'no,don't turn it ON
			Labelbluetoothstatus.Text="OFF"
			Buttonbluetoothswitch.Text="TURN ON"
			disable_main_views
		End If
		connected=False	'may be if previously connected and user has turned off bluetooth manually off the application pausing it
	Else'if bluetooth is ON
		Buttonconnect.Enabled=True
		Labelbluetoothstatus.Text="ON"
		Buttonbluetoothswitch.Text="TURN OFF"
	End If	
End Sub
Sub Activity_Pause (UserClosed As Boolean)

End Sub


'###################################################################### ANIMATION 
Sub animate2_AnimationEnd	'main animation is over now
	t2.Enabled=True	'wait for 1.5 second now
End Sub
Sub t1_tick	'main animation routine
	Select i
		Case 0 : Label3.Visible=True
		Case 1 : Label4.Visible=True
		Case 2 : Label5.Visible=True
		Case 3 : ImageView2.Visible=True
		Case 4 : t1.Enabled=False
				 mp.Load(File.DirAssets,"welcome.wav")
				 mp.Play
				 Label1.Visible=True
				 Label2.Visible=True
				 animate1.Start(Label1)
				 animate2.Start(Label2)
	End Select
	
	If i>=0 AND i<=3 Then
		mp.Load(File.DirAssets,"ding.wav")
		mp.Play
	End If
	
	i = i + 1
End Sub
Sub t2_tick	'after 1.5 second front page animation is over now, now load the actual application interface
	t2.Enabled=False
	Panelappliances.Visible=True	'this will be the default panel to be displyed first
	Panelappliances.BringToFront 'now bring it to front first
	panimate1.Start(Panelappliances) 'start the fading animation for this panel	
	panimate1.Duration=700'now change the panel fade animation timings to 700ms
	
	'now try to connect to the previously registered host device (if bluetooth is enabled)
	If badmin.IsEnabled=True Then
		If File.ReadString(File.DirInternal,"mac.txt")<>"" Then 'some default MAC address exists and app need to be connected to this automatically
			Dim m As String
			m = File.ReadString(File.DirInternal,"mac.txt")'read the MAC address stored
			serial1.Connect(m)'connect to it automatically
		End If	
	End If
End Sub


'###################################################################### MENU BUTTONS 
Sub mnuappliances_click
	Panelappliances.Visible=True
	Panelsensors.Visible=False
	Panelsensomate.Visible=False
	Paneldoor.Visible=False
	Panelsettings.Visible=False
	Panelabout.Visible=False
	
	Panelappliances.BringToFront	'bring this panel to front
	mp.Load(File.DirAssets,"appliancecontrol.wav")
    mp.Play
End Sub
Sub mnusensors_click
	Panelsensors.Visible=True
	Panelappliances.Visible=False
	Panelsensomate.Visible=False
	Paneldoor.Visible=False
	Panelsettings.Visible=False
	Panelabout.Visible=False
	
	Panelsensors.BringToFront	'bring this panel to front
	mp.Load(File.DirAssets,"sensors.wav")
    mp.Play
End Sub
Sub mnudoor_click
	Paneldoor.Visible=True
	Panelappliances.Visible=False
	Panelsensors.Visible=False
	Panelsensomate.Visible=False
	Panelsettings.Visible=False
	Panelabout.Visible=False
	
	Paneldoor.BringToFront	'bring this panel to front
	mp.Load(File.DirAssets,"door control.wav")
    mp.Play
End Sub
Sub mnusensomate_click
	Panelsensomate.Visible=True
	Panelappliances.Visible=False
	Panelsensors.Visible=False
	Paneldoor.Visible=False
	Panelsettings.Visible=False
	Panelabout.Visible=False
	
	Panelsensomate.BringToFront	'bring this panel to front
	mp.Load(File.DirAssets,"sensomate.wav")
    mp.Play
End Sub
Sub mnusettings_click
	Panelsettings.Visible=True	
	Panelappliances.Visible=False
	Panelsensors.Visible=False
	Panelsensomate.Visible=False
	Paneldoor.Visible=False
	Panelabout.Visible=False
	
	Panelsettings.BringToFront	'bring this panel to front
	mp.Load(File.DirAssets,"settings.wav")
    mp.Play
End Sub
Sub mnuabout_click
	Panelsettings.Visible=False
	Panelappliances.Visible=False
	Panelsensors.Visible=False
	Panelsensomate.Visible=False
	Paneldoor.Visible=False
	Panelabout.Visible=True
	
	Panelabout.BringToFront	'bring this panel to front
	mp.Load(File.DirAssets,"about.wav")
    mp.Play
End Sub

'###################################################################### BLUETOOTH ADAPTOR ON/OFF 
Sub Buttonbluetoothswitch_Click
	If Buttonbluetoothswitch.Text="TURN ON" Then 'bluettoth is previously OFF
		Buttonbluetoothswitch.Text="TURN OFF"
		badmin.enable	'turn bluetooth ON
	Else 'bluettoth is previously ON
		If connected=True Then'if previously connected
			astreams.Close
			serial1.Disconnect
			connected = False  
			disable_main_views
		End If
		Buttonbluetoothswitch.Text="TURN ON"
		badmin.disable	'turn bluetooth OFF
	End If	
End Sub
Sub badmin_statechanged(newstate As Int,oldstate As Int)'state change event of bluetooth adaptor
    'The adapter will not be immediately ready. You should use the StateChanged event to find when it is enabled/disabled
	If newstate=badmin.STATE_ON Then'if bluetooth switched ON successfuly
		ToastMessageShow("Bluetooth is switched ON!",False)
		Labelbluetoothstatus.Text="ON"
		Buttonbluetoothswitch.Text="TURN OFF"
		Buttonconnect.Enabled=True
		Buttonconnect.Text="CONNECT"
	End If
	
	If newstate=badmin.STATE_OFF Then'if bluetooth switched OFF successfuly
		ToastMessageShow("Bluetooth is switched OFF!",False)
		Labelbluetoothstatus.Text="OFF"
		Buttonbluetoothswitch.Text="TURN ON"
		Buttonconnect.Enabled=False
	End If
	
	If newstate=badmin.STATE_TURNING_OFF Then'if bluetooth is turning OFF
		ToastMessageShow("Turning OFF bluetooth!",False)
		Labelbluetoothstatus.Text="-----"
		disable_main_views
	End If
	
	If newstate=badmin.STATE_TURNING_ON Then'if bluetooth is turning ON
		ToastMessageShow("Turning ON bluetooth!",False)
		Labelbluetoothstatus.Text="-----"
	End If
End Sub
'###################################################################### ENABLE/DISABLE VIEWS 
Sub enable_main_views
	Buttonfanoff.Enabled=True
	Buttonfanon.Enabled=True
	Buttonlight1off.Enabled=True
	Buttonlight1on.Enabled=True
	Buttonlight2off.Enabled=True
	Buttonlight2on.Enabled=True
	Buttontvoff.Enabled=True
	Buttontvon.Enabled=True
	Buttonallon.Enabled=True
	Buttonalloff.Enabled=True
	Buttondoor.Enabled=True
	Buttonsenlight1.Enabled=True
	Buttonsenlight2.Enabled=True
	Buttonsenfan.Enabled=True
	Buttonsenmotion.Enabled=True
	Buttonsavelog.Enabled=True
	Buttonconnect.Enabled=True
	Buttonsleepmode.Enabled=True
	Buttonsleepmodeoff.Enabled=True
	Labeltempout.Text="000"
	Labeltempin.Text="000"
	Labellightout.Text="000"
	Labellightin.Text="000"
	Labelmotion.Text="NO MOTION"
	Labellpg.Text="NO LEAK"
	Buttonprogfire.Enabled=True
End Sub

Sub disable_main_views
	Buttonfanoff.Enabled=False
	Buttonfanon.Enabled=False
	Buttonlight1off.Enabled=False
	Buttonlight1on.Enabled=False
	Buttonlight2off.Enabled=False
	Buttonlight2on.Enabled=False
	Buttontvoff.Enabled=False
	Buttontvon.Enabled=False
	Buttonallon.Enabled=False
	Buttonalloff.Enabled=False
	Buttondoor.Enabled=False
	Buttonsenlight1.Enabled=False
	Buttonsleepmode.Enabled=False
	Buttonsenlight2.Enabled=False
	Buttonsenfan.Enabled=False
	Buttonsenmotion.Enabled=False
	Buttonsavelog.Enabled=False
	Buttonconnect.Enabled=False
	Buttonsleepmodeoff.Enabled=False
	Buttonprogfire.Enabled=False
	
	Labeltempout.Text="000"
	Labeltempin.Text="000"
	Labellightout.Text="000"
	Labellightin.Text="000"
	Labelmotion.Text="NO MOTION"
	Labellpg.Text="NO LEAK"
	
	'reset color indiacators 
	Buttonlight1on.TextColor=Colors.Black
	Buttonlight1off.TextColor=Colors.black
	Buttonlight2on.TextColor=Colors.black
	Buttonlight2off.TextColor=Colors.black
	Buttontvon.TextColor=Colors.black
	Buttontvoff.TextColor=Colors.black
	Buttonfanon.TextColor=Colors.black
	Buttonfanoff.TextColor=Colors.black
	Buttonsleepmode.Textcolor=Colors.black
	Buttonsleepmodeoff.Textcolor=Colors.black
	
	Buttondoor.Text="OPEN"
	Imagedoorstatus.Bitmap=LoadBitmap(File.DirAssets,"close_door.png")'closed gate graphic loading
	Labeldoorstatus.Text="DOOR CLOSED"
	
	Buttonsenmotion.Text="Unprogrammed"
	Buttonsenlight1.Text="Unprogrammed"
	Buttonsenlight2.Text="Unprogrammed"
	Buttonsenfan.Text="Unprogrammed"
End Sub


'###################################################################### APPLIANCES CONTROL 
'--------------------------------TV
Sub Buttontvon_Click
	s="C"
	astreams.Write(s.GetBytes("UTF8"))
End Sub
Sub Buttontvoff_Click
	s="c"
	astreams.Write(s.GetBytes("UTF8"))
End Sub

'--------------------------------Light2
Sub Buttonlight2on_Click
	s="B"
	astreams.Write(s.GetBytes("UTF8"))
End Sub
Sub Buttonlight2off_Click
	s="b"
	astreams.Write(s.GetBytes("UTF8"))
End Sub

'--------------------------------Light1
Sub Buttonlight1on_Click
	s="A"
	astreams.Write(s.GetBytes("UTF8"))
End Sub
Sub Buttonlight1off_Click
	s="a"
	astreams.Write(s.GetBytes("UTF8"))
End Sub

'--------------------------------FAN
Sub Buttonfanon_Click
	s="D"
	astreams.Write(s.GetBytes("UTF8"))
End Sub
Sub Buttonfanoff_Click
	s="d"
	astreams.Write(s.GetBytes("UTF8"))
End Sub

'--------------------------------All Devices
Sub Buttonallon_Click'
	s="E"
	astreams.Write(s.GetBytes("UTF8"))
End Sub
Sub Buttonalloff_Click
	s="e"
	astreams.Write(s.GetBytes("UTF8"))
End Sub


'###################################################################### SENSOMATE 
Sub Buttonsenlight1_Click
	numdial.Decimal=0
	numdial.Digits=2
	numdial.Number=15
	numdial.ShowSign=False
	Dim r As Byte
	r=numdial.Show("Light1 lower limit(%) :","Prog","Cancel","Unprog",Null)
	If r=DialogResponse.POSITIVE Then'programme the threshold value
		If numdial.Number<5 Then 'if user wrongly enters value greater less then 5%
			Msgbox("Please enter the limit greater than 5% !","Error")
			Return
		End If
		
		Dim one As Byte,two As Byte,i As Int
		one =numdial.Number Mod 10'fetch ones place number
		two =numdial.Number / 10'fetch tens place number
		
		'frame and send code
		s="H"
		astreams.Write(s.GetBytes("UTF8"))
			For i=1 To 20000'wait some time
			Next 
		s=two
		astreams.Write(s.GetBytes("UTF8"))
			For i=1 To 20000
			Next 
		s=one
		astreams.Write(s.GetBytes("UTF8"))
			For i=1 To 20000
			Next 
		s="h"
		astreams.Write(s.GetBytes("UTF8"))
		
	Else If r=DialogResponse.NEGATIVE Then'unprogramme the threshold value
		s="I"
		astreams.Write(s.GetBytes("UTF8"))
	End If
End Sub

Sub Buttonsenlight2_Click
	numdial.Decimal=0
	numdial.Digits=2
	numdial.Number=15
	numdial.ShowSign=False
	Dim r As Byte
	r=numdial.Show("Light2 lower limit(%) :","Prog","Cancel","Unprog",Null)
	If r=DialogResponse.POSITIVE Then'programme the threshold value
		If numdial.Number<5 Then 'if user wrongly enters value greater less then 5%
			Msgbox("Please enter the limit greater than 5% !","Error")
			Return
		End If
		
		Dim one As Byte,two As Byte,i As Int
		one =numdial.Number Mod 10'fetch ones place number
		two =numdial.Number / 10'fetch tens place number
		
		'frame and send code
		s="J"
		astreams.Write(s.GetBytes("UTF8"))
			For i=1 To 20000'wait some time
			Next 
		s=two
		astreams.Write(s.GetBytes("UTF8"))
			For i=1 To 20000
			Next 
		s=one
		astreams.Write(s.GetBytes("UTF8"))
			For i=1 To 20000
			Next 
		s="j"
		astreams.Write(s.GetBytes("UTF8"))
		
	Else If r=DialogResponse.NEGATIVE Then'unprogramme the threshold value
		s="K"
		astreams.Write(s.GetBytes("UTF8"))
	End If
End Sub

Sub Buttonsenfan_Click
	numdial.Decimal=0
	numdial.Digits=2
	numdial.Number=32
	numdial.ShowSign=False
	Dim r As Byte
	r=numdial.Show("Fan/AC lower limit('C) :","Prog","Cancel","Unprog",Null)
	If r=DialogResponse.POSITIVE Then'programme the threshold value
		If numdial.Number<10 Then 'if user wrongly enters value greater less then 10'c
			Msgbox("Please enter the limit less between 10'C - 99'C !","Error")
			Return
		End If
		
		Dim one As Byte,two As Byte,i As Int
		one =numdial.Number Mod 10'fetch ones place number
		two =numdial.Number / 10'fetch tens place number
		
		'frame and send code
		s="L"
		astreams.Write(s.GetBytes("UTF8"))
			For i=1 To 20000'wait some time
			Next 
		s=two
		astreams.Write(s.GetBytes("UTF8"))
			For i=1 To 20000
			Next 
		s=one
		astreams.Write(s.GetBytes("UTF8"))
			For i=1 To 20000
			Next 
		s="l"
		astreams.Write(s.GetBytes("UTF8"))
		
	Else If r=DialogResponse.NEGATIVE Then'unprogramme the threshold value
		s="M"
		astreams.Write(s.GetBytes("UTF8"))
	End If
End Sub
Sub Buttonsenmotion_Click
	Dim r As Byte
	r=Msgbox2("Do you want to program the motion sensor to switch ON Light2(outside) if motion is detected on the entrance?","Motion sensor alarm","Prog","Cancel","Unprog",Null)
	If r=DialogResponse.POSITIVE Then'programme the alarm
		s="G"
		astreams.Write(s.GetBytes("UTF8"))
	Else If r=DialogResponse.NEGATIVE Then'unprogramme the alarm
		s="g"
		astreams.Write(s.GetBytes("UTF8"))
	End If
End Sub
Sub Buttonsleepmode_Click'turn ON sleep mode
		s="S"
		astreams.Write(s.GetBytes("UTF8"))
End Sub
Sub Buttonsleepmodeoff_Click'turn OFF sleep mode
		s="T"
		astreams.Write(s.GetBytes("UTF8"))
End Sub


'###################################################################### SETTINGS 
Sub Buttonconnect_Click
	If Buttonconnect.Text="CONNECT" Then'if disconnected previously
			If connected=False Then'if you are disconnected
				Dim PairedDevices As Map
				PairedDevices = serial1.GetPairedDevices 
				
				Dim l As List  'create a list
				l.Initialize 'iniitialize the list
				
				For i = 0 To PairedDevices.Size - 1     
					l.Add(PairedDevices.GetKeyAt(i)) 'add the friendly name to the list  
				Next
				
				Dim res As Int  
				res = InputList(l, "Choose device",-1) 'show list with paired devices 
				If res <> DialogResponse.CANCEL Then'if user has not pressed the back key       
				    serial1.Connect(PairedDevices.Get(l.Get(res))) 'convert the name to mac address   
					File.WriteString(File.DirInternal,"mac.txt",PairedDevices.Get(l.Get(res)))'store the file with currently chosen paired host's MAC address
				End If
			End If
	Else  'if connected previously
			disable_main_views
			Buttonconnect.Enabled=True
			Buttonconnect.Text="CONNECT"
			astreams.Close
			serial1.Disconnect
			connected = False
			ToastMessageShow("Disconnected successfully!",False)
	End If
End Sub
Sub Serial1_Connected (Success As Boolean)'this event is raised when a connection is established successfully
	If Success Then'if successfully connected
	    astreams.Initialize(serial1.InputStream,serial1.OutputStream, "AStreams")
		'Once there is a connection we initialize the AsyncStreams object
		ToastMessageShow("Connected to the host server successfully with " & Chr(10)& "MAC address:" & Chr(10)& serial1.Address & Chr(10) & "Name:" &Chr(10)& serial1.Name, False)  'here chr(10) is line feed
		connected = True
		enable_main_views
		Buttonconnect.Text="DISCONNECT"
	Else'if no success in connection
		astreams.Close
		serial1.Disconnect
		connected = False  
		disable_main_views
		Buttonconnect.Enabled=True
		Buttonconnect.Text="CONNECT"
		ToastMessageShow("Connection to the host server failed,please try again", False)  
	End If
End Sub
Sub AStreams_NewData (Buffer() As Byte)'serial data will be received here
    'When new data is available the NewData event is raised with the data
    'Then when there is new data available we convert the bytes to string and show it
    Dim msg As String
    msg = BytesToString(Buffer, 0,Buffer.length, "UTF8")
	msg = msg.trim
	
	If msg.StartsWith("@")=True AND msg.EndsWith("#")=True Then'complete string is received
		sb = msg
		fullrx = True
	Else If msg.StartsWith("@")=True AND msg.EndsWith("#")=False Then'Starting string is received
		sb = msg
		fullrx = False
	Else If msg.StartsWith("@")=False AND msg.EndsWith("#")=True Then'ending string is received
		sb = sb & msg	'concatinate it and make it full
		fullrx = True
	Else 
		fullrx = False
	End If
	
	If fullrx = True Then		'now if we got the complete data string
	    If sb.Length >= 44 AND sb.Length < = 49 Then'if valid string is received,its length cannot go beyond this limit
			Try	
				If sb.charat(1)=Chr(90)Then		'Z ligh1 turned ON by host
					Buttonlight1on.TextColor=Colors.green
					Buttonlight1off.TextColor=Colors.black
				Else If sb.charat(1)=Chr(122)Then		'z ligh1 turned Off by host
					Buttonlight1on.TextColor=Colors.black
					Buttonlight1off.TextColor=Colors.green
				End If

				If sb.charat(2)= Chr(89)Then		'Y ligh2 turned ON by host
					Buttonlight2on.TextColor=Colors.green
					Buttonlight2off.TextColor=Colors.black
				Else If sb.charat(2)= Chr(121)Then		'y ligh2 turned Off by host
					Buttonlight2on.TextColor=Colors.black
					Buttonlight2off.TextColor=Colors.green
				End If
				
				If sb.charat(3)= Chr(88)Then'X
					Buttontvon.TextColor=Colors.green
					Buttontvoff.TextColor=Colors.black
				Else If sb.charat(3)=  Chr(120)Then'x
					Buttontvon.TextColor=Colors.black
					Buttontvoff.TextColor=Colors.green
				End If
				
				If sb.charat(4)= Chr(87)Then'W
					Buttonfanon.TextColor=Colors.green
					Buttonfanoff.TextColor=Colors.black
				Else If sb.charat(4)=  Chr(119)Then'w
					Buttonfanon.TextColor=Colors.black
					Buttonfanoff.TextColor=Colors.green
				End If
				
				If sb.charat(5)= Chr(70)Then'F
					Labelmotion.Text="YES"
				Else If sb.charat(5)= Chr(102)Then'f
					Labelmotion.Text="NO"
				End If
				
				If sb.charat(6)= Chr(71)Then'G
					Labellpg.Text="LEAK"
				Else If sb.charat(6)= Chr(103)Then'g
					Labellpg.Text="NO LEAK"
				End If	
				
				If sb.charat(7)= Chr(85)Then'U door is opened now
					Buttondoor.Text="CLOSE"
					Imagedoorstatus.Bitmap=LoadBitmap(File.DirAssets,"open_door.png")'opened gate graphic loading
					Labeldoorstatus.Text="DOOR OPENED"
				Else If sb.charat(7)= Chr(117)Then'u door is closed now
					Buttondoor.Text="OPEN"
					Imagedoorstatus.Bitmap=LoadBitmap(File.DirAssets,"close_door.png")'closed gate graphic loading
					Labeldoorstatus.Text="DOOR CLOSED"
				End If	
					
				If sb.charat(8)= Chr(84)Then'T sleep mode activated
					Buttonsleepmode.Textcolor=Colors.green
					Buttonsleepmodeoff.Textcolor=Colors.black
				Else If sb.charat(8)= Chr(116)Then't sleep mode deactivated
					Buttonsleepmode.Textcolor=Colors.black
					Buttonsleepmodeoff.Textcolor=Colors.green
				End If	
					
				If sb.charat(9)= Chr(83)Then'S motion sensor alarm programmed
					Buttonsenmotion.Text="Programmed"
				Else If sb.charat(9)= Chr(115)Then's motion sensor alarm unprogrammed
					Buttonsenmotion.Text="Unprogrammed"
				End If	
				
				Dim start As Byte
				Dim finish As Byte
								
				'extract temperature inside value
				start = sb.IndexOf("K")
				finish = sb.IndexOf("k")
				If (start>=0 AND start<=sb.Length) AND (finish>=0 AND finish<=sb.Length) Then'if the both are in limits
					Labeltempin.text = sb.SubString2(start+1,finish)
				End If
				
				'extract temperature outside value
				start = sb.IndexOf("J")
				finish = sb.IndexOf("j")
				If (start>=0 AND start<=sb.Length) AND (finish>=0 AND finish<=sb.Length) Then'if the both are in limits
					Labeltempout.text = sb.SubString2(start+1,finish)
				End If
				
				'extract light inside value
				start = sb.IndexOf("I")
				finish = sb.IndexOf("i")
				If (start>=0 AND start<=sb.Length) AND (finish>=0 AND finish<=sb.Length) Then'if the both are in limits
					Labellightin.text = sb.SubString2(start+1,finish)
				End If
				
				'extract light inside value
				start = sb.IndexOf("H")
				finish = sb.IndexOf("h")
				If (start>=0 AND start<=sb.Length) AND (finish>=0 AND finish<=sb.Length) Then'if the both are in limits
					Labellightout.text = sb.SubString2(start+1,finish)
				End If
				
				Dim x As String
				
				'extract programmed light1 value
				start = sb.IndexOf("R")
				finish = sb.IndexOf("r")
				If (start>=0 AND start<=sb.Length) AND (finish>=0 AND finish<=sb.Length) Then'if the both are in limits
					x = sb.SubString2(start+1,finish)
					If x="0" Then
						Buttonsenlight1.text ="Unprogrammed"
					Else	
						Buttonsenlight1.Text="Programmed = " & x
					End If
				End If
				
				'extract programmed light2 value
				start = sb.IndexOf("P")
				finish = sb.IndexOf("p")
				If (start>=0 AND start<=sb.Length) AND (finish>=0 AND finish<=sb.Length) Then'if the both are in limits
					x = sb.SubString2(start+1,finish)
					If x="0" Then
						Buttonsenlight2.text ="Unprogrammed"
					Else	
						Buttonsenlight2.Text="Programmed = " & x
					End If
				End If
				
				'extract programmed fan value
				start = sb.IndexOf("N")
				finish = sb.IndexOf("n")
				If (start>=0 AND start<=sb.Length) AND (finish>=0 AND finish<=sb.Length) Then'if the both are in limits
					x = sb.SubString2(start+1,finish)
					If x="0" Then
						Buttonsenfan.text ="Unprogrammed"
					Else	
						Buttonsenfan.Text="Programmed = " & x
					End If
				End If
			Catch'any exception raised in the try-catch block will be caught here
				'ToastMessageShow(LastException.Message,False)
			End Try
		End If
	End If			
End Sub
Sub Buttonresetautoconnect_Click
	File.WriteString(File.DirInternal,"mac.txt","")'store the file with null,means no autoconnection will be done at startup
	ToastMessageShow("Autoconnection disabled successfully!",False)
End Sub
Sub Buttonpassword_Click
	If File.ReadString(File.DirInternal,"password.txt")<>"" Then 'if some password exists
		inpbox.InputType=inpbox.INPUT_TYPE_TEXT
		inpbox.PasswordMode=True
		inpbox.Input=""
		If inpbox.Show("","Enter current password :","OK","Cancel","",Null)=DialogResponse.POSITIVE Then'if user entered something and hit OK
			If inpbox.Input<>File.ReadString(File.DirInternal,"password.txt") Then 'current password not matched
				Msgbox("Incorrect password,try again!","Error")
				Return
			End If
		Else 'if user cancelled enetering password
			Return	'return from here only
		End If
	End If
	
	Dim a As Byte
	a=Msgbox2("Do you want to change the password?","Password Manager","Yes","No","Disable",Null)
	If a=DialogResponse.NEGATIVE Then'disable the password
		File.WriteString(File.DirInternal,"password.txt","")'file stored with no text means password is disabled
		ToastMessageShow("Password disabled successfully!",False)
	Else If a= DialogResponse.POSITIVE Then 'change the password
		inpbox.InputType=inpbox.INPUT_TYPE_TEXT
		inpbox.PasswordMode=True
		inpbox.Input=""
		If inpbox.Show("","Enter new password :","OK","Cancel","",Null)=DialogResponse.POSITIVE Then
			File.WriteString(File.DirInternal,"password.txt",inpbox.Input)
			ToastMessageShow("Password changed successfully!",False)
		End If
	End If
End Sub
Sub Buttonprogfire_Click
	numdial.Decimal=0
	numdial.Digits=2
	numdial.Number=48
	numdial.ShowSign=False
	If numdial.Show("Fire alarm threshold ('C) min :","OK","Cancel","",Null)=DialogResponse.POSITIVE Then
		If numdial.Number>=30 AND numdial.Number<=80 Then'if user entered between 30-80'C
			
			Dim one As Byte,two As Byte,i As Int
			one =numdial.Number Mod 10'fetch ones place number
			two =numdial.Number / 10'fetch tens place number
			
			'frame and send code
			s="P"
			astreams.Write(s.GetBytes("UTF8"))
				For i=1 To 20000'wait some time
				Next 
			s=two
			astreams.Write(s.GetBytes("UTF8"))
				For i=1 To 20000
				Next 
			s=one
			astreams.Write(s.GetBytes("UTF8"))
				For i=1 To 20000
				Next 
			s="p"
			astreams.Write(s.GetBytes("UTF8"))
		
		Else
			Msgbox("You can programme the fire sensor threshold only between 30'C-80'C!","Error")
		End If
	End If
End Sub

'###################################################################### DOOR CONTROL 
Sub Buttondoor_Click'door OPEN/CLOSE button
	If Buttondoor.Text="OPEN" Then 'gate is previously closed,button is dislaying "OPEN"
		s="F"'open the door command
		astreams.Write(s.GetBytes("UTF8"))
	Else 'gate is previously opened,button is dislaying "CLOSE"
		s="N"'close the door command
		astreams.Write(s.GetBytes("UTF8"))
	End If	
End Sub


'###################################################################### HELP 
Sub Imagesettings_Click
	mp.Load(File.DirAssets,"help_settings.wav")
	mp.Play
	Msgbox("With this,you can change the device settings for serial communication over bluetooth!","HELP")
End Sub
Sub Imagesensors_Click
	mp.Load(File.DirAssets,"help_sensors.wav")
	mp.Play
	Msgbox("With this,you can monitor temperature and light conditions outside and inside of your home!","HELP")
End Sub
Sub Imagesensomate_Click
	mp.Load(File.DirAssets,"help_sensomate.wav")
	mp.Play
	Msgbox("With this,you can automate your lights and fan/AC to switch ON/OFF automatically when the light and temperature of your home exceeds a programmable threshold value, and also your motion sensor to activate outdoor light on activity at main door!","HELP")
End Sub
Sub Imagedoor_Click
	mp.Load(File.DirAssets,"help_door.wav")
	mp.Play
	Msgbox("With this,you can check and control your main entrance door!","HELP")
End Sub
Sub Imageappliance_Click
	mp.Load(File.DirAssets,"help_appliances.wav")
	mp.Play
	Msgbox("With this,you can manually switch ON/OFF your home appliances!","HELP")
End Sub
Sub Buttonsenmotion_LongClick
	Msgbox("With this,you can program the motion sensor to switch ON Light2(outside)when motion is detected at the entrance door","Help")
End Sub
Sub Buttonsenlight2_LongClick
	Msgbox("With this,you can program LIGHT2 to switch ON/OFF automatically when the external light sensor exceeds the programmed threshold value!","Help")
End Sub
Sub Buttonsenlight1_LongClick
	Msgbox("With this,you can program LIGHT1 to switch ON/OFF automatically when the external light sensor exceeds the programmed threshold value!","Help")
End Sub
Sub Buttonsenfan_LongClick
	Msgbox("With this,you can program Fan/AC to switch ON/OFF automatically when the internal temperature sensor exceeds the programmed threshold value!","Help")
End Sub
Sub Buttonsavelog_LongClick
	Msgbox("With this,you can save your current sensor readings to your SD card!","Help")
End Sub
Sub Buttonpassword_LongClick
	Msgbox("With this,you can set and change you login password!","Help")
End Sub
Sub Buttondoor_LongClick
	Msgbox("With this,you can manually open/close your main entrance door!","Help")
End Sub
Sub Buttonconnect_LongClick
	Msgbox("With this,you can manually connect/disconnect with your host device!","Help")
End Sub
Sub Buttonbluetoothswitch_LongClick
	Msgbox("With this,you can manually turn ON/OFF the phones's bluetooth adaptor!","Help")
End Sub
Sub Buttonallon_LongClick
	Msgbox("With this,you can turn ON all your home appliances in a single click!","Help")
End Sub
Sub Buttonalloff_LongClick
	Msgbox("With this,you can turn OFF all your home appliances in a single click!","Help")
End Sub
Sub Buttonresetautoconnect_LongClick
	Msgbox("With this,you can disable the autoconnection at startup of your app to the previously registered host!","Help")
End Sub
Sub Buttonsleepmode_LongClick
	Msgbox("With this,you can activate the sleep mode which will turn off all devices and, activate the door and motion alarm so that you can sleep with no worries!","Help")
End Sub
Sub Buttonsleepmodeoff_LongClick
	Msgbox("With this,you can deactivate the sleep mode!","Help")
End Sub
Sub Buttonprogfire_LongClick
	Msgbox("With this,you can programme the host to raise fire alarm if the temperature inside home exceeds this threshold limit!","Help")
End Sub

'###################################################################### OTHER ROUTINES AND EVENTS
Sub Buttonsavelog_Click
	Dim s As String,filename As String
	'build the filename(time and date will be the filename)for the file to be stored with
	DateTime.TimeFormat="HH,mm,ss"
	DateTime.DateFormat="MM.dd.yyyy"
	filename=DateTime.Time(DateTime.Now) & "_" & DateTime.date(DateTime.Now) & ".txt"
	'build the sensor reading string to be stored in the text file
	s="Temperature outside : " & Labeltempout.Text & CRLF & "Temperature inside : " & Labeltempin.Text & CRLF & "Light outside : " & Labellightout.Text & CRLF & "Light inside : " & Labellightin.Text & CRLF &  "Motion : " & Labelmotion.Text & CRLF & "LPG : " & Labellpg.text & CRLF & CRLF & "Time : " & DateTime.Time(DateTime.Now) & CRLF & "Date : " & DateTime.date(DateTime.Now)
	'now create the file and write all the data to the file
	File.WriteString("/mnt/sdcard/smarthome",filename,s)
	ToastMessageShow("Sensor readings logged successfully!",False)
End Sub
Sub Activity_KeyPress (KeyCode As Int) As Boolean 'Return True to consume the event
	If KeyCode=KeyCodes.KEYCODE_BACK Then'if user pressed the back key
		If connected=False Then'if the application was previously disconnected
			Return False'means now this activity keypress event is not consumed and transmitted to the system for further actions which is supposed to be performed by the respective (BACK)key pressed
		Else'if previously connected
			ToastMessageShow("Current connection disconnected!" & Chr(10) & "Press back again to exit!",False)
			disable_main_views
			astreams.Close
			serial1.Disconnect
			connected=False
			Buttonconnect.Enabled=True
			Buttonconnect.Text="CONNECT"
			Return True'this event is consumed and no further action is taken
		End If
	End If
End Sub







