Ejemplo n.º 1
0
	def test_Iperf_TCP_Na(self):
		rs232_putty = RS232_Putty()
		rs232_putty.RS232_Connect_Putty()
		os.system("adb shell am force-stop com.magicandroidapps.iperf")
		android = Android()
		adbClient = AdbClient()

		for i in range(1,int(config.get("setting","run_times"))+1):
			
			for j in range(1,int(config.get("iperf_setting", "times"))+1):
				self.Del_File("result.txt")
				iperf_command = "-s -i 5"
				# adbClient.Swiandroidh_Iperf()
				self.Mobile_Device_Connect()
				self.Killall_Iperf()
				adbClient.Service_Iperf_Start_N('iperf '+iperf_command)
				self.Iperf_Log_Clean()
				adbClient.Iperf_Client()
				adbClient.Getfile_Command_Iperf()
				os.system("adb shell input keyevent 4")
				android.Screen_Shot_Save("iperf_tcp_na")
				android.Mobile_Device_Disconnect()
				adbClient.Strip_Split_Iperf()
				adbClient.Move_File("Down_")
				adbClient.Split_Move_File("Down_split_")
Ejemplo n.º 2
0
 def Click_Device_Value0(self):
     time.sleep(80)
     if d(text=config_setting.get("setting", "PLMN")).exists:
         d(text=config_setting.get("setting", "PLMN")).click()
         android = Android()
         android.Copy_Trace_Folder()
         raise Exception("The device is clicked. - FAIL")
     else:
         print "The device is not clicked. - PASS"
Ejemplo n.º 3
0
    def test_Ftp_Download_With_Handy(self):
        os.system("adb shell am force-stop com.ftpcafe")
        os.system("adb shell am force-stop com.anite.handy")
        android = Android()
        adbClient = AdbClient()
        run_times = config.get("setting", "run_times")
        times = config.get("ftp_setting", "times")
        filename = config.get("ftp_setting", "filename_handy")
        filestart = config.get("ftp_setting", "filename_handy")
        fileend = config.get("ftp_setting", "filename_handy_size")
        print "NB Server & android Client (ftp loop download)"

        for i in range(1, int(run_times) + 1):

            for j in range(1, int(times) + 1):
                self.Swiandroidh_FtpClient()
                self.Mobile_Device_Connect()
                # adbClient.Download_Over()
                # android.Ftp_Creat_Account()
                #*******************Download from 10.1.107.213*****************
                # print 'Donwload Times: ' + str(j)
                # self.Ftplog_Renew()
                # self.Ftp_Autoselect_Server('server')
                # self.Ftp_Connect()
                # self.Verify_Ftp_Connect()
                # self.Folder_Select("Downloads")
                # self.Ftp_Download(filename)

                #****************** Download from speed.hine.net***************
                self.Ftp_Autoselect_Server('hinet')
                self.Ftp_Connect()
                self.Verify_Ftp_Connect()
                print 'Donwload Times: ' + str(j)
                time.sleep(10)
                self.Ftp_Download(filename)

                #*******************Handy function ****************************
                self.Swiandroidh_Handy()
                self.Mobile_Device_Connect()
                time.sleep(28)
                print "mobile_device_connect is success."
                time.sleep(1)
                self.Switch_Voice_Quality(j)
                self.Handy_Start_Script()
                time.sleep(1)
                self.Handy_Run_Script()
                print "Run script."
                time.sleep(112)
                self.Screen_Shot_Save("Volte")
                time.sleep(25)
                self.Handy_Keep_Log()
                time.sleep(5)
                self.Get_Handy_Folder()

        android.Mobile_Device_Disconnect()
        print "mobile_device_disconnect"
Ejemplo n.º 4
0
	def ACS_Initiate_Connection(self):
		try:
			self.System_Operation_Data()
			self.Click_Serial_Number()
			time.sleep(2)
			selenium.click(
				"link="+config_element.get("system", "system_message_queue"))
			print "Click the message queue"
			for i in range(2):
				selenium.click(
					"xpath="+config_element.get("system", "system_refresh_button"))
				print "Click the refresh " + str(i+1) + " times"
			# Verify the SetParameterValues text can be get
			# time.sleep(1)  # Wait the 1 sec for get the acs parametervalues text on 106/06/11
			setParameterValues = selenium.get_text(
				"xpath="+config_element.get("detail_message", "acs_parametervalues_text"))
			if setParameterValues == 'SetParameterValues':
				print 'Get the SetParameterValues text!!'
			else:
				print "Do not Get the SetParameterValues text!!"
				android = Android()
				android.Copy_Trace_Folder()
				raise Exception("Do not Get the SetParameterValues text!!")
			self.Autoit_Tab_button(38, 200)
			autoit.Sleep(2000)
			autoit.Send("{ENTER}")
			print 'Click the ACS TCP Initiate Connection was finished'
			autoit.Sleep(2000)
			# IE 9
			autoit.WinWaitActive(
				"[title:ACS Notify Page - Windows Internet Explorer]", "")
			autoit.ControlClick(
				"ACS Notify Page - Windows Internet Explorer", "", "ToolbarWindow321")
			self.Autoit_Tab_button(4, 100)
			autoit.Sleep(2000)
			autoit.Send("{ENTER}")
			autoit.Sleep(2000)
			delete_subfolder = Delete_Subfolder()
			delete_subfolder.Delete_Path_Subfolder("..\\..\\Result\\femtolog")
			adbClient = AdbClient()
			time.sleep(2)
			adbClient.Swiandroidh_ACS()
			autoit.WinClose("[class:IEFrame]")
			# Click the refresh button
			for i in range(1):
				selenium.click(
					"xpath="+config_element.get("system", "system_refresh_button"))
				print "Click the refresh " + str(i+1) + " times"
			autoit.Sleep(2000)
			print "Click the acs initiate connectin button"
		except:
			raise Exception("The ace initiate button was not click - FAIL")
Ejemplo n.º 5
0
    def __init__(self, file_path):
        Svg.__init__(self)
        Writer.__init__(self)
        Magic.__init__(self)

        self.io_dir = os.path.dirname(
            os.path.dirname(os.path.abspath(file_path)))
        self.res_dir = os.path.join(self.io_dir, 'res')

        self.android = Android()

        self.file_path = file_path
        self.parse()
Ejemplo n.º 6
0
    def __init__(self):
        threading.Thread.__init__(self)

        #self.pc = PC(tcp_ip="192.168.1.1")
        self.android = Android()
        self.arduino = Arduino()

        #self.pc.connect()
        self.android.connect()
        self.arduino.connect()

        time.sleep(1)

        self.interface = Interface(arduino=self.arduino,
                                   fakeRun=False,
                                   android=self.android)
Ejemplo n.º 7
0
 def Speed_Test(self, filename):
     android = Android()
     adbClient = AdbClient()
     print "Speed_Test"
     # adbClient.Swiandroidh_Speedtest()
     android.Mobile_Device_Connect()
     time.sleep(2)
     android.Verify_Speed()
     time.sleep(40)
     android.Speed_Download()
     android.Speed_Upload()
     android.Screen_Shot_Save(filename)
     android.Mobile_Device_Disconnect()
Ejemplo n.º 8
0
    def test_Ftp_Download_Server(self):
        os.system("adb shell am force-stop com.ftpcafe")
        android = Android()
        adbClient = AdbClient()
        run_times = config.get("setting", "run_times")
        times = config.get("ftp_setting", "times")
        filename = config.get("ftp_setting", "filename_download")
        filestart = config.get("ftp_setting", "filename_download")
        fileend = config.get("ftp_setting", "filename_download_size")
        print "NB Server & android Client (ftp loop download)"
        self.Swiandroidh_FtpClient()

        for i in range(1, int(run_times) + 1):
            android.Mobile_Device_Connect()
            # self.Download_Over()
            # self.Ftp_Creat_Account()

            for j in range(1, int(times) + 1):
                print 'Donwload Times: ' + str(j)
                self.Ftplog_Renew()
                self.Ftp_Autoselect_Server('server')
                self.Ftp_Connect()
                self.Verify_Ftp_Connect()
                self.Folder_Select("Downloads")
                self.Ftp_Download(filename)
                print "The filename is " + filename
                self.Del_File("..\..\\Result\\log\\vsftpd.log")
                self.Transfer_Status(filestart, fileend)
                self.Getfile_Command()
                self.Check_File_Status()
                self.ADB_Event("4")
                self.Screen_Shot_Save("FTP_Download")
                self.FTP_Drate()
                self.ADB_Event("66")
                self.ADB_Event("66")
                self.ADB_Event("111")
                self.ADB_Event("111")
                self.ADB_Event("111")

        self.Mobile_Device_Disconnect()
        print "mobile_device_disconnect"
Ejemplo n.º 9
0
def start_script_proxy(toast_message=START_MESSAGE, server_wait=1.0, retries=10):

	adb = lambda cmd, ADB=ADB: sh("%s %s"%(ADB, cmd))

	# Start TCP forwarding
	adb("forward tcp:%i tcp:%i"%(HOST_PORT, REMOTE_PORT))


	proxy = Android(addr=(None, HOST_PORT))
	start_message = lambda: proxy.makeToast(toast_message)

	try:
		# Try if we are already connected SL4A will start the server with
		# a random port if it's already running regardless of the
		# USE_SERVICE_PORT parameter
		start_message()
		return proxy # We seem to be connected
	except socket.error, e:
		# Try to start the server
		adb("shell am start "
		    "-a com.googlecode.android_scripting.action.LAUNCH_SERVER "
		    "-n com.googlecode.android_scripting/.activity.ScriptingLayerServiceLauncher "
		    "--ei com.googlecode.android_scripting.extra.USE_SERVICE_PORT %i"%SL4A_PORT)
Ejemplo n.º 10
0
    def Click_Device_Value1(self, device):
        for search_times in range(
                int(config_setting.get("search_times", "times"))):
            time.sleep(1)
            self.Switch_Back()
            time.sleep(1)
            print 'The Research times : ' + str(search_times + 1)
            self.Switch_Network_Operators()

            # Judgment the PLMN number by nexus or note4
            plmn = config_setting.get("setting", "PLMN")
            merge_plmn = plmn.split(" ")[0] + plmn.split(" ")[1]

            if device == 'nexus':
                print 'The device is nexus.'
                time.sleep(180)
                if d(text=plmn).exists:
                    print 'nexus'
                    d(text=plmn).click()
                    break

            if device == 'note4':
                print 'The device is note4.'
                self.Information_Alert()
                # time.sleep(95)
                time.sleep(180)
                if d(text=merge_plmn).exists:
                    print 'note4'
                    d(text=merge_plmn).click()
                    break

            if search_times + 1 == int(
                    config_setting.get("search_times", "times")):
                android = Android()
                android.Copy_Trace_Folder()
                raise Exception("The device is not clicked. - FAIL")
        print "The device is clicked. - PASS"
Ejemplo n.º 11
0
def start_script_proxy(toast_message=START_MESSAGE, server_wait=1.0, retries=10):

    adb = lambda cmd, ADB=ADB: sh("%s %s" % (ADB, cmd))

    # Start TCP forwarding
    adb("forward tcp:%i tcp:%i" % (HOST_PORT, REMOTE_PORT))

    proxy = Android(addr=(None, HOST_PORT))
    start_message = lambda: proxy.makeToast(toast_message)

    try:
        # Try if we are already connected SL4A will start the server with
        # a random port if it's already running regardless of the
        # USE_SERVICE_PORT parameter
        start_message()
        return proxy  # We seem to be connected
    except socket.error, e:
        # Try to start the server
        adb(
            "shell am start "
            "-a com.googlecode.android_scripting.action.LAUNCH_SERVER "
            "-n com.googlecode.android_scripting/.activity.ScriptingLayerServiceLauncher "
            "--ei com.googlecode.android_scripting.extra.USE_SERVICE_PORT %i" % SL4A_PORT
        )
Ejemplo n.º 12
0
	def HeNS_Request_Message(self, boolean, heMS_SetParameterValues):
		# try:
			pyautogui.click(1000, 30)
			self.System_Operation_Data()
			self.Click_Serial_Number()
			# Click the Message Log #
			selenium.click(
				"link="+config_element.get("system", "system_message_log"))
			# Refresh the list content
			for refresh in range(2):
				selenium.click(
					"xpath="+config_element.get("system", "system_refresh_button"))
			# Select the HeMS detail message
			print 'Type the serial number.'
			self.Click_CheckBox()
			selenium.type("id="+config_element.get("detail_message",
												   "search_askey_root"), config_element.get("detail_message", "input_askey_root"))
			time.sleep(3)
			selenium.click(
				"xpath="+config_element.get("detail_message", "search_button"))
			print "Select the key code"
			# Verify the SetParameterValues text can be get
			setParameterValues = selenium.get_text(
				"xpath="+config_element.get("detail_message", "parametervalues_text"))
			if setParameterValues == 'SetParameterValues':
				print 'Get the SetParameterValues text!!'
			else:
				print "Do not Get the SetParameterValues text!!"
				android = Android()
				android.Copy_Trace_Folder()
				raise Exception("Do not Get the SetParameterValues text!!")
			self.Autoit_Detail_Message(40)
			# Get the message from Get_clipboard
			message_log_detail_dialog = self.Get_Clipboard()
			# Verify the boolean value
			if '<Value xsi:type="boolean">' + boolean + '</Value>' in message_log_detail_dialog:
				print 'The boolean was matched - SUCCESS'
			elif '<Value xsi:type="boolean">' + 'true' + '</Value>' in message_log_detail_dialog:
				print 'The boolean was matched - SUCCESS'
			elif '<Value xsi:type="boolean">' + 'false' + '</Value>' in message_log_detail_dialog:
				print 'The boolean was matched - SUCCESS'
			else:
				print "The boolean was not matched - FAIL"
				android = Android()
				android.Copy_Trace_Folder()
				raise Exception("The boolean was not matched - FAIL")
			time.sleep(1)
			now = time.strftime("%Y-%m-%d-%H_%M_%S",
								time.localtime(time.time()))
			heMS_SetParameterValues = heMS_SetParameterValues + '_' + now + '.txt'
			fp = open(heMS_SetParameterValues, "w")
			fp.write(message_log_detail_dialog)
			autoit.Sleep(1000)
			autoit.Send("!{F4}")
			print "Close the Detail page"
Ejemplo n.º 13
0
 def setUp(self):
     print 'Start by Automated execution.'
     global scp, ssh, rs232_putty
     global android, adbClient, uiautomator_control
     global reboot_command, customer_nl_local, customer_remote
     global plmn
     global boolean
     scp = SCP()
     ssh = SSH()
     rs232_putty = RS232_Putty()
     uiautomator_control = Uiautomator_Control()
     android = Android()
     adbClient = AdbClient()
     reboot_command = './rsys/scripts/reboot-fap'
     customer_nl_local = 'customer.nl'
     customer_remote = 'customer.rcS'
     plmn = "123-45"
Ejemplo n.º 14
0
	def test_Ftp_Upload_Server(self):
		os.system("adb shell am force-stop com.ftpcafe")
		android = Android()
		adbClient = AdbClient()
		run_times = config.get("setting","run_times")
		times = config.get("ftp_setting","times")
		filename = config.get("ftp_setting", "filename_upload")
		filestart = config.get("ftp_setting", "filename_upload")
		fileend = config.get("ftp_setting", "filename_upload_size")
		print "NB Server & android Client (ftp loop upload)"
		adbClient.Swiandroidh_FtpClient()

		for i in range(1,int(run_times)+1):
			self.Mobile_Device_Connect()
			# adbClient.Download_Over()
			# android.Ftp_Creat_Account()

			for j in range(1,int(times)+1):	
				print 'Upload Times: ' + str(i)
				self.Ftplog_Renew()
				self.Ftp_Autoselect_Server('server')
				self.Ftp_Connect()
				self.Verify_Ftp_Connect()
				self.Folder_Select("Uploads")
				self.Ftp_Localfolder()
				self.ADB_Event("123")
				self.ADB_Event("123")
				self.Folder_Select("Uploads")
				self.Ftp_Upload(filename)
				self.Transfer_Status(filestart,fileend)
				self.Getfile_Command()
				self.Check_File_Status()
				self.ADB_Event("4")
				self.Screen_Shot_Save("FTP_Upload")
				self.FTP_Urate()
				self.ADB_Event("66")
				self.ADB_Event("66")
				self.ADB_Event("111")
				self.ADB_Event("111")
				self.ADB_Event("111")
				
		self.mobile_device_disconnect()
		print "mobile_device_disconnect"
Ejemplo n.º 15
0
	def HeNB_Response_Message(self, status, heNB_SetParameterValuesResponse):
		try:
			pyautogui.click(1000, 30)
			self.System_Operation_Data()
			self.Click_Serial_Number()
			# Click the Message Log #
			selenium.click(
				"link="+config_element.get("system", "system_message_log"))
			# Select the HeNB detail message
			print 'Type the serial number.'
			self.Click_CheckBox()
			time.sleep(3)
			selenium.click(
				"xpath="+config_element.get("detail_message", "search_button"))
			print "Select the key code"
			# Verify the SetParameterValuesResponse text can be get
			setParameterValuesResponse = selenium.get_text(
				"xpath="+config_element.get("detail_message", "parametervalues_text"))
			if setParameterValuesResponse == 'SetParameterValuesResponse':
				print 'Get the SetParameterValuesResponse text!!'
			else:
				print "Do not Get the SetParameterValues text!!"
				android = Android()
				android.Copy_Trace_Folder()
				raise Exception("Do not Get the SetParameterValues text!!")
			self.Autoit_Detail_Message(40)
			# Get the message from Get_clipboard
			message_log_detail_dialog = self.Get_Clipboard()
			# Verify the status value
			if '<Status>' + status + '</Status>' in message_log_detail_dialog:
				print 'The status was matched - SUCCESS'
			else:
				print "The status was not matched - FAIL"
				android = Android()
				android.Copy_Trace_Folder()
				raise Exception("The status was not matched - FAIL")
			time.sleep(1)
			now = time.strftime("%Y-%m-%d-%H_%M_%S",
								time.localtime(time.time()))
			heNB_SetParameterValuesResponse = heNB_SetParameterValuesResponse + '_' + now + '.txt'
			fp = open(heNB_SetParameterValuesResponse, "w")
			fp.write(message_log_detail_dialog)
			autoit.Sleep(1000)
			autoit.Send("!{F4}")
			print "Close the Detail page"
		except:
			raise Exception("The HeNB_Response_Message was not success - FAIL")
Ejemplo n.º 16
0
    def test_Iperf_TCP_An(self):
        rs232_putty = RS232_Putty()
        rs232_putty.RS232_Connect_Putty()
        os.system("adb shell am force-stop com.magicandroidapps.iperf")
        android = Android()
        adbClient = AdbClient()

        for i in range(1, int(config.get("setting", "run_times")) + 1):

            for j in range(1, int(config.get("iperf_setting", "times")) + 1):
                adbClient.Del_File("result.txt")
                iperf_command = "-s -i 5"
                time.sleep(2)
                # adbClient.Swiandroidh_Iperf()
                android.Mobile_Device_Connect()
                android.Service_Iperf_Start(iperf_command)
                android.Iperf_Log_Clean()
                adbClient.Get_Android_IP()
                adbClient.Client_Iperf_Start()
                android.Screen_Shot_Save("iperf_tcp_an")
                android.Mobile_Device_Disconnect()
                adbClient.Strip_Split_Iperf()
                adbClient.Move_File("Up_")
                adbClient.Split_Move_File("Up_split_")
Ejemplo n.º 17
0
 def FTP_NA_Download(self):
     android = Android()
     adbClient = AdbClient()
     filename = "1.pdf"
     filestart = "/1.pdf"
     fileend = "104857600 bytes"
     print "NB Server & android Client (ftp download)"
     adbClient.swiandroidh_FtpClient()
     adbClient.ftplog_renew()
     android.mobile_device_connect()
     adbClient.download_over()
     android.ftp_creataccount()
     android.ftp_connect()
     android.Verify_ftp_connect()
     android.folder_select("Download")
     android.ftp_download(filename)
     adbClient.Transfer_Status(filestart, fileend)
     adbClient.getfile_command()
     adbClient.Check_FileStatus()
     adbClient.adb_event("4")
     android.screen_shot_save("FTP_Download")
     adbClient.FTP_Drate()
     android.mobile_device_disconnect()
Ejemplo n.º 18
0
import json
import time
from android import Android

droid = Android()
# dt = 100ms
dt = 0.1
droid.startSensingTimed(1, dt)
droid.webViewShow('file:///sdcard/sl4a/scripts' +
                  '/SensorGraph/Accelerometer/accUI.html')
xList = [0] * 20
yList = [0] * 20
zList = [0] * 20

def postAccelerometerValues():
    xyzList = droid.sensorsReadAccelerometer().result

    xList.append(xyzList[0])
    yList.append(xyzList[1])
    zList.append(xyzList[2])

    del xList[0]
    del yList[0]
    del zList[0]

    xyzDict = {"x":xList, "y":yList, "z":zList}
    droid.eventPost('stdout', json.dumps(xyzDict))

while True:
    postAccelerometerValues()
    time.sleep(0.3)
Ejemplo n.º 19
0
from android import Android
import time

droid = Android()

defH = int (input ('Hora (0-23): '))
defM = int (input ('Minuto (0-59): '))
texto = input ('Texto ("despierta"): ')

while True:
    h = int (time.strftime ('%H'))
    m = int (time.strftime ('%M'))
    if (h == defH and m >= defM):
        droid.ttsSpeak (texto)
        print (texto)
    time.sleep(10)
Ejemplo n.º 20
0
#-*-coding:utf8;-*-
#qpy:3
#qpy:console

from android import Android

droid = Android()
#set
droid.toggleBluetoothState(1)
#toggle
#droid.toggleBluetoothState()
Ejemplo n.º 21
0
 def flash_images(self, images):
     fimgs = list()
     avb = None
     for image in images:
         if image == 'fw':
             self.flash_firmware('{path}/{fw}'.format(path=self._flashfiles,
                                                      fw=self._fw))
         elif image == 'ioc':
             self.flash_ioc('{path}/{fw}'.format(path=self._flashfiles,
                                                 fw=self._ioc))
         else:
             # avb make images.
             d.info('update %s image' % image)
             if avb == None:
                 avb = AvbImage()
             avb.avb_make_image(image, self)
             fimgs.append(image)
     # flash images.
     if len(fimgs) != 0:
         fimgs.append('vbmeta')
         # setup flash env
         ad = Android()
         #ad.adb_wait()
         # enter bootloader mode.
         ad.run_cmd_handler(['rebootloader'])
         # unlock
         ad.run_cmd_handler(['deviceunlock'])
         # flash image now
         for image in fimgs:
             fimage = r'{}/{}.img'.format(self._flashfiles, image)
             d.info('fastboot flash {} {}'.format(image, fimage))
             ad.flash_image(image, fimage)
         # lock device.
         ad.run_cmd_handler(['devicelock'])
         # reboot
         ad.run_cmd_handler(['fastreboot'])
Ejemplo n.º 22
0
import json
import time
from android import Android

droid = Android()
# dt = 100ms
dt = 0.1
droid.startSensingTimed(1, dt)
droid.webViewShow('file:///sdcard/sl4a/scripts' +
                  '/SensorGraph/OrientationSensor/gyroUI.html')
xList = [0] * 20
yList = [0] * 20
zList = [0] * 20

def postOrientationSensorValues():
    xyzList = droid.sensorsReadOrientation().result

    xList.append(xyzList[0])
    yList.append(xyzList[1])
    zList.append(xyzList[2])

    del xList[0]
    del yList[0]
    del zList[0]

    xyzDict = {"x":xList, "y":yList, "z":zList}
    droid.eventPost('stdout', json.dumps(xyzDict))

while True:
    postOrientationSensorValues()
    time.sleep(0.3)
#-*-coding:utf8;-*-
#qpy:3
#qpy:console

from android import Android 
import pprint

droid = Android()
apps = droid.getLaunchableApplications()
pprint.pprint(apps.result)
Ejemplo n.º 24
0
from android import Android
import time

droid = Android()
droid.webViewShow('file:///sdcard/sl4a/scripts/Examples/index.html',True)

time.sleep(5)
Ejemplo n.º 25
0
	def build_and_run(self, install, avd_id, keystore=None, keystore_pass='******', keystore_alias='tidev', dist_dir=None):
		deploy_type = 'development'
		if install:
			if keystore == None:
				deploy_type = 'test'
			else:
				deploy_type = 'production'
				
		aapt = os.path.join(self.tools_dir,'aapt')
		jar = os.path.join(self.platform_dir,'android.jar')
		dx = os.path.join(self.tools_dir,'dx')
		apkbuilder = os.path.join(self.sdk,'tools','apkbuilder')
		if platform.system() == "Windows":
			aapt += ".exe"
			dx += ".bat"
			apkbuilder += ".bat"
		
		if keystore==None:
			keystore = os.path.join(self.support_dir,'dev_keystore')
		
		curdir = os.getcwd()
		tijar = os.path.join(self.support_dir,'titanium.jar')
		timapjar = os.path.join(self.support_dir,'titanium-map.jar')
		
		try:
			os.chdir(self.project_dir)
			
			if os.path.exists('bin'):
				shutil.rmtree('bin')
			os.makedirs('bin')
			
			if os.path.exists('lib'):
				shutil.copy(tijar,'lib')

			resources_dir = os.path.join(self.top_dir,'Resources')
			assets_dir = os.path.join('bin','assets')
			asset_resource_dir = os.path.join(assets_dir,'Resources')

			# we re-run the create each time through in case any of our key files
			# have changed
			android = Android(self.name,self.app_id,self.sdk)
			android.create(os.path.abspath(os.path.join(self.top_dir,'..')),True)

			# transform resources
			def strip_slash(s):
				if s[0:1]=='/' or s[0:1]=='\\': return s[1:]
				return s
			def recursive_cp(dir,dest):
				for root, dirs, files in os.walk(dir):
					# Remove file from the list of files copied
					# that shouldn't appear in the binaries
					for name in ignoreFiles:
						if name in files:
							files.remove(name);
					for name in ignoreDirs:
						if name in dirs:
							dirs.remove(name)
					# Copy remaining files
					relative = strip_slash(root.replace(dir,''))
					relative_dest = os.path.join(dest,relative)
					if not os.path.exists(relative_dest):
						os.makedirs(relative_dest)
					for f in files:
						fullpath = os.path.join(root,f)
						relativedest = os.path.join(dest,relative,f)
						print "[TRACE] COPYING: %s => %s" %(fullpath,relativedest)
						shutil.copy(fullpath,relativedest)

			if os.path.exists(asset_resource_dir):
				shutil.rmtree(asset_resource_dir)
			os.makedirs(asset_resource_dir)
			recursive_cp(resources_dir,asset_resource_dir)
			if os.path.exists(os.path.join(asset_resource_dir,'iphone')):
				shutil.rmtree(os.path.join(asset_resource_dir,'iphone'))
			if os.path.exists(os.path.join(resources_dir,'android')):
				recursive_cp(os.path.join(resources_dir,'android'),asset_resource_dir)		
				shutil.rmtree(os.path.join(asset_resource_dir,'android'))
				


			sys.stdout.flush()

			if not os.path.exists(assets_dir):
				os.makedirs(assets_dir)
				
			my_avd = None	
			google_apis_supported = False
				
			# find the AVD we've selected and determine if we support Google APIs
			for avd_props in avd.get_avds(self.sdk):
				if avd_props['id'] == avd_id:
					my_avd = avd_props
					google_apis_supported = (my_avd['name'].find('Google')!=-1)
					break

			# compile resources
			full_resource_dir = os.path.join(self.project_dir,asset_resource_dir)
			compiler = Compiler(self.app_id,full_resource_dir,False)
			compiler.compile()
			
			# Android SDK version --- FIXME: this is hardcoded until i hook in Nolan's code from Developer
			android_sdk_version = '3'
			
			# NOTE: these are built-in permissions we need -- we probably need to refine when these are needed too
			permissions_required = ['INTERNET','ACCESS_WIFI_STATE','ACCESS_NETWORK_STATE']
			
			GEO_PERMISSION = [ 'ACCESS_COARSE_LOCATION', 'ACCESS_FINE_LOCATION', 'ACCESS_MOCK_LOCATION']
			CONTACTS_PERMISSION = ['READ_CONTACTS']
			VIBRATE_PERMISSION = ['VIBRATE']
			CAMERA_PERMISSION = ['CAMERA']
			
			# this is our module method to permission(s) trigger - for each method on the left, require the permission(s) on the right
			permission_mapping = {
				# GEO
				'Geolocation.watchPosition' : GEO_PERMISSION,
				'Geolocation.getCurrentPosition' : GEO_PERMISSION,
				'Geolocation.watchHeading' : GEO_PERMISSION,
				'Geolocation.getCurrentHeading' : GEO_PERMISSION,
				
				# MEDIA
				'Media.vibrate' : VIBRATE_PERMISSION,
				'Media.createVideoPlayer' : CAMERA_PERMISSION,
				'Media.showCamera' : CAMERA_PERMISSION,
				
				# CONTACTS
				'Contacts.createContact' : CONTACTS_PERMISSION,
				'Contacts.saveContact' : CONTACTS_PERMISSION,
				'Contacts.removeContact' : CONTACTS_PERMISSION,
				'Contacts.addContact' : CONTACTS_PERMISSION,
				'Contacts.getAllContacts' : CONTACTS_PERMISSION,
				'Contacts.showContactPicker' : CONTACTS_PERMISSION,
			}
			
			VIDEO_ACTIVITY = """<activity
			android:name="org.appcelerator.titanium.TitaniumVideoActivity"
			android:configChanges="keyboardHidden|orientation"
			android:launchMode="singleTask"
	    	/>"""
	
			MAP_ACTIVITY = """<activity
	    		android:name="org.appcelerator.titanium.module.map.TitaniumMapActivity"
	    		android:configChanges="keyboardHidden|orientation"
	    		android:launchMode="singleTask"
	    	/>
		<uses-library android:name="com.google.android.maps" />"""
	
			FACEBOOK_ACTIVITY = """<activity 
			android:name="org.appcelerator.titanium.module.facebook.FBActivity"
			android:theme="@android:style/Theme.Translucent.NoTitleBar"
        />"""
			
			activity_mapping = {
			
				# MEDIA
				'Media.createVideoPlayer' : VIDEO_ACTIVITY,
				
				# MAPS
				'Map.createView' : MAP_ACTIVITY,
		    	
				# FACEBOOK
				'Facebook.setup' : FACEBOOK_ACTIVITY,
				'Facebook.login' : FACEBOOK_ACTIVITY,
				'Facebook.createLoginButton' : FACEBOOK_ACTIVITY,
			}
			
			# this is a map of our APIs to ones that require Google APIs to be available on the device
			google_apis = {
				"Map.createView" : True
			}
			
			activities = []
			
			# figure out which permissions we need based on the used module methods
			for mn in compiler.module_methods:
				try:
					perms = permission_mapping[mn]
					if perms:
						for perm in perms: 
							try:
								permissions_required.index(perm)
							except:
								permissions_required.append(perm)
				except:
					pass
				try:
					mappings = activity_mapping[mn]
					try:
						if google_apis[mn] and not google_apis_supported:
							print "[WARN] Google APIs detected but a device has been selected that doesn't support them. The API call to Titanium.%s will fail using '%s'" % (mn,my_avd['name'])
							sys.stdout.flush()
							continue
					except:
						pass
					try:
						activities.index(mappings)
					except:
						activities.append(mappings)
				except:
					pass
			
			# build the permissions XML based on the permissions detected
			permissions_required_xml = ""
			for p in permissions_required:
				permissions_required_xml+="<uses-permission android:name=\"android.permission.%s\"/>\n\t" % p				
			
			# copy any module image directories
			for module in compiler.modules:
				if module.lower() == 'map' and google_apis_supported:
					tijar = timapjar
					print "[INFO] Detected Google Maps dependency. Using Titanium + Maps"
				img_dir = os.path.abspath(os.path.join(template_dir,'modules',module.lower(),'images'))
				if os.path.exists(img_dir):
					dest_img_dir = os.path.join(full_resource_dir,'modules',module.lower(),'images')
					if os.path.exists(dest_img_dir):
						shutil.rmtree(dest_img_dir)
					os.makedirs(dest_img_dir)
					copy_resources(img_dir,dest_img_dir)
				

			shutil.copy(os.path.join(self.top_dir,'tiapp.xml'), assets_dir)
			
			tiapp = open(os.path.join(assets_dir, 'tiapp.xml')).read()
			
			finalxml = os.path.join(assets_dir,'tiapp.xml')
			tiapp = TiAppXML(finalxml)
			tiapp.setDeployType(deploy_type)
			
			iconname = tiapp.properties['icon']
			iconpath = os.path.join(asset_resource_dir,iconname)
			iconext = os.path.splitext(iconpath)[1]
			if not os.path.exists(os.path.join('res','drawable')):
				os.makedirs(os.path.join('res','drawable'))
				
			existingicon = os.path.join('res','drawable','appicon%s' % iconext)	
			if os.path.exists(existingicon):	
				os.remove(existingicon)
			if os.path.exists(iconpath):
				shutil.copy(iconpath,existingicon)

			# make our Titanium theme for our icon
			resfiledir = os.path.join('res','values')
			if not os.path.exists(resfiledir):
				os.makedirs(resfiledir)
			resfilepath = os.path.join(resfiledir,'theme.xml')
			if not os.path.exists(resfilepath):
				resfile = open(resfilepath,'w')
				TITANIUM_THEME="""<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.Titanium" parent="android:Theme">
        <item name="android:windowBackground">@drawable/background</item>
    </style>
</resources>
	"""
				resfile.write(TITANIUM_THEME)
				resfile.close()
			
			# create our background image which acts as splash screen during load	
			splashimage = os.path.join(asset_resource_dir,'default.png')
			if os.path.exists(splashimage):
				print "[DEBUG] found splash screen at %s" % os.path.abspath(splashimage)
				shutil.copy(splashimage,os.path.join('res','drawable','background.png'))
			
			

			src_dir = os.path.join(self.project_dir, 'src')
			android_manifest = os.path.join(self.project_dir, 'AndroidManifest.xml')
			
			android_manifest_to_read = android_manifest

			# NOTE: allow the user to use their own custom AndroidManifest if they put a file named
			# AndroidManifest.custom.xml in their android project directory in which case all bets are
			# off
			android_custom_manifest = os.path.join(self.project_dir, 'AndroidManifest.custom.xml')
			if os.path.exists(android_custom_manifest):
				android_manifest_to_read = android_custom_manifest
				print "[INFO] Detected custom ApplicationManifest.xml -- no Titanium version migration supported"
			
			# we need to write out the new manifest
			manifest_contents = open(android_manifest_to_read,'r').read()
			manifest_contents = manifest_contents.replace('<!-- TI_ACTIVITIES -->',"\n\n\t\t".join(activities))
			manifest_contents = manifest_contents.replace('<!-- TI_PERMISSIONS -->',permissions_required_xml)
			manifest_contents = manifest_contents.replace('<uses-sdk android:minSdkVersion="3" />', '<uses-sdk android:minSdkVersion="%s" />' % android_sdk_version)

			# write out the new manifest
			amf = open(android_manifest,'w')
			amf.write(manifest_contents)
			amf.close()
			
			res_dir = os.path.join(self.project_dir, 'res')
			output = run.run([aapt, 'package', '-m', '-J', src_dir, '-M', android_manifest, '-S', res_dir, '-I', jar])
			if output == None:
				sys.exit(1)
			success = re.findall(r'ERROR (.*)',output)
			if len(success) > 0:
				print "[ERROR] %s" % success[0]
				sys.exit(1)
			
			srclist = []
			jarlist = []
						
			for root, dirs, files in os.walk(os.path.join(self.project_dir,'src')):
				# Strip out directories we shouldn't traverse
				for name in ignoreDirs:
					if name in dirs:
						dirs.remove(name)
						
				if len(files) > 0:
					for f in files:
						if f in ignoreFiles : continue
						path = root + os.sep + f
						srclist.append(path)
		
			project_module_dir = os.path.join(self.top_dir,'modules','android')
			if os.path.exists(project_module_dir):
				for root, dirs, files in os.walk(project_module_dir):
					# Strip out directories we shouldn't traverse
					for name in ignoreDirs:
						if name in dirs:
							dirs.remove(name)

					if len(files) > 0:
						for f in files:
							path = root + os.sep + f
							ext = splitext(f)[-1]
							if ext in ('.java'):
								srclist.append(path)
							elif ext in ('.jar'):
								jarlist.append(path) 
				
		
			classes_dir = os.path.join(self.project_dir, 'bin', 'classes')	
			if not os.path.exists(classes_dir):
				os.makedirs(classes_dir)

			jarsigner = "jarsigner"	
			javac = "javac"
			if platform.system() == "Windows":
				if os.environ.has_key("JAVA_HOME"):
					home_jarsigner = os.path.join(os.environ["JAVA_HOME"], "bin", "jarsigner.exe")
					home_javac = os.path.join(os.environ["JAVA_HOME"], "bin", "javac.exe")
					if os.path.exists(home_jarsigner):
						jarsigner = home_jarsigner
					if os.path.exists(home_javac):
						javac = home_javac
				else:
					found = False
					for path in os.environ['PATH'].split(os.pathsep):
						if os.path.exists(os.path.join(path, 'jarsigner.exe')) and os.path.exists(os.path.join(path, 'javac.exe')):
							jarsigner = os.path.join(path, 'jarsigner.exe')
							javac = os.path.join(path, 'javac.exe')
							found = True
							break
					if not found:
						print "[ERROR] Error locating JDK: set $JAVA_HOME or put javac and jarsigner on your $PATH"
						sys.exit(1)
						
			# see if the user has app data and if so, compile in the user data
			# such that it can be accessed automatically using Titanium.App.Properties.getString
			app_data_cfg = os.path.join(self.top_dir,"appdata.cfg")
			if os.path.exists(app_data_cfg):
				props = read_properties(open(app_data_cfg,"r"))
				module_data = ''
				for key in props.keys():
					data = props[key]
					module_data+="properties.setString(\"%s\",\"%s\");\n   " % (key,data)
					print("[DEBUG] detected user application data at = %s"% app_data_cfg)
					sys.stdout.flush()
					dtf = os.path.join(src_dir,"AppUserData.java")
					if os.path.exists(dtf):
						os.remove(dtf)
					ctf = open(dtf,"w")
					cf_template = open(os.path.join(template_dir,'templates','AppUserData.java'),'r').read()
					cf_template = cf_template.replace('__MODULE_BODY__',module_data)
					ctf.write(cf_template)
					ctf.close()
					srclist.append(dtf)
						
			classpath = jar + os.pathsep + tijar + os.pathsep.join(jarlist)
			
			javac_command = [javac, '-classpath', classpath, '-d', classes_dir, '-sourcepath', src_dir]
			javac_command += srclist
			print "[DEBUG] %s" % javac_command
			sys.stdout.flush()
			out = run.run(javac_command)
			
		
			classes_dex = os.path.join(self.project_dir, 'bin', 'classes.dex')	
			if platform.system() == "Windows":
				run.run([dx, '--dex', '--output='+classes_dex, classes_dir, tijar])
			else:
				run.run([dx, '-JXmx512M', '--dex', '--output='+classes_dex, classes_dir, tijar])
										
			ap_ = os.path.join(self.project_dir, 'bin', 'app.ap_')	
			run.run([aapt, 'package', '-f', '-M', 'AndroidManifest.xml', '-A', assets_dir, '-S', 'res', '-I', jar, '-I', tijar, '-F', ap_])
		
			unsigned_apk = os.path.join(self.project_dir, 'bin', 'app-unsigned.apk')	
			run.run([apkbuilder, unsigned_apk, '-u', '-z', ap_, '-f', classes_dex, '-rf', src_dir, '-rj', tijar])
	
			if dist_dir:
				app_apk = os.path.join(dist_dir, project_name + '.apk')	
			else:
				app_apk = os.path.join(self.project_dir, 'bin', 'app.apk')	

			output = run.run([jarsigner, '-storepass', keystore_pass, '-keystore', keystore, '-signedjar', app_apk, unsigned_apk, keystore_alias])
			success = re.findall(r'RuntimeException: (.*)',output)
			if len(success) > 0:
				print "[ERROR] %s " %success[0]
				sys.exit(1)
				
			# NOTE: we can't zipalign until we officially support 1.6+
			# # attempt to zipalign -- this only exists in 1.6 and above so be nice
			# zipalign = os.path.join(self.tools_dir,'zipalign')
			# if platform.system() == "Windows":
			# 	zipalign+=".exe"
			# 	
			# if os.path.exists(zipalign):
			# 	#zipalign -v 4 source.apk destination.apk
			# 	run.run([zipalign, '-v', '4', app_apk, app_apk+'z'])
			# 	os.rename(app_apk+'z',app_apk)

			if dist_dir:
				sys.exit(0)			

			out = subprocess.Popen([self.adb,'get-state'], stderr=subprocess.PIPE, stdout=subprocess.PIPE).communicate()[0]
			out = str(out).strip()
			
			# try a few times as sometimes it fails waiting on boot
			attempts = 0
			launched = False
			launch_failed = False
			while attempts < 5:
				try:
					cmd = [self.adb]
					if install:
						self.wait_for_device('d')
						print "[INFO] Installing application on emulator"
						cmd += ['-d', 'install', '-r', app_apk]
					else:
						self.wait_for_device('e')
						print "[INFO] Installing application on device"
						cmd += ['-e', 'install', '-r', app_apk]
					if run.run(cmd)==None:
						launch_failed = True
					elif not install:
						launched = True
					break
				except:
					time.sleep(3)
					attempts+=1

			if launched:
				print "[INFO] Launching application ... %s" % self.name
				sys.stdout.flush()
				run.run([self.adb, '-e' , 'shell', 'am', 'start', '-a', 'android.intent.action.MAIN', '-c','android.intent.category.LAUNCHER', '-n', '%s/.%sActivity' % (self.app_id , self.classname)])
				print "[INFO] Deployed %s ... Application should be running." % self.name
			elif launch_failed==False:
				print "[INFO] Application installed. Launch from drawer on Home Screen"

		finally:
			os.chdir(curdir)
			sys.stdout.flush()
Ejemplo n.º 26
0
def gui(maps_M):
    xmaps_M = []
    droid = Android()
    droid.dialogCreateAlert('Checkbox')
    droid.dialogSetMultiChoiceItems(maps_M)
    droid.dialogSetPositiveButtonText('Download')
    droid.dialogShow()

    while not droid.dialogGetResponse().result['which'] == 'positive':
        pass
    xmaps_num = droid.dialogGetSelectedItems().result
    print(xmaps_num)
    for i in xmaps_num:
        xmaps_M.append(maps_M[i])
    return xmaps_M
Ejemplo n.º 27
0
#importamos las librerias que utiliza la aplicación
import sys
import math
import time 

#el siguiente coduigo es escencial para que el dialogCreateAlert funcione
from android import Android
droid = Android()
 
#Primera llamada de la aplicacion con el interprete de android
mensaje1='Hola, me llamo Contador, y te dire cuanto te mueves en 30 segundos'
droid.ttsSpeak(mensaje1)

# tiempo de espera en segundos para ejecucion del siguiente codigo
time.sleep(5)

#Mensaje de dialogo
droid.dialogCreateAlert('Cuenta pasos', '¿Listo para iniciar?')
 
droid.dialogSetPositiveButtonText('Si')
droid.dialogSetNegativeButtonText('No')
 
droid.dialogShow()

#dependiendo de la respuesta escogida en el dialogo será el resultado, si es no la opcion escogida se despide el interprete y 
#se finaliza la aplicacion, si es si inicia la aplicacion para contar los pasos aproximados en 8 segundos

response = droid.dialogGetResponse().result
droid.dialogDismiss()
 
if not 'which' in response or response['which'] != 'positive': 
Ejemplo n.º 28
0
 def FTP_NA_Upload(self):
     android = Android()
     adbClient = AdbClient()
     times = "1"
     filename = "2.pdf"
     filestart = "/2.pdf"
     fileend = "62914560 bytes"
     print "NB Server & android Client (ftp upload)"
     adbClient.swiandroidh_FtpClient()
     adbClient.ftplog_renew()
     android.mobile_device_connect()
     adbClient.download_over()
     android.ftp_creataccount()
     android.ftp_connect()
     android.Verify_ftp_connect()
     android.folder_select("Upload")
     android.ftp_localfolder()
     adbClient.adb_event("123")
     adbClient.adb_event("123")
     android.folder_select("Upload")
     android.ftp_upload(filename)
     adbClient.Transfer_Status(filestart, fileend)
     adbClient.getfile_command()
     adbClient.Check_FileStatus()
     adbClient.adb_event("4")
     android.screen_shot_save("FTP_Upload")
     adbClient.FTP_Urate()
     android.mobile_device_disconnect()
Ejemplo n.º 29
0
#This is a program that handles the actual image processing and
#answer detection. We are going to build mobile apps based on this
#program and hopefully we will be able to add more functionality to it.
import cv2
from android import Android
droid = Android()
import numpy as np


def rectify(h):
    h = h.reshape((4, 2))
    hnew = np.zeros((4, 2), dtype=np.float32)
    add = h.sum(1)
    hnew[0] = h[np.argmin(add)]
    hnew[2] = h[np.argmax(add)]

    diff = np.diff(h, axis=1)
    hnew[1] = h[np.argmin(diff)]
    hnew[3] = h[np.argmax(diff)]

    return hnew


def check_include(centre_list, x_centre, y_centre):
    for point in centre_list:
        x_difference = point[0] - x_centre
        y_difference = point[1] - y_centre
        if abs(x_difference) < 10 and abs(y_difference) < 10:
            return False
    return True
Ejemplo n.º 30
0
 def FTP_NA_Upload_S(self):
     android = Android()
     adbClient = AdbClient()
     print "NB Server & android Client (ftp upload)"
     adbClient.swiandroidh_FtpClient()
     android.mobile_device_connect()
     adbClient.download_over()
     android.ftp_creataccount()
     for i in range(0, int(times)):
         adbClient.ftplog_renew()
         android.ftp_connect()
         android.Verify_ftp_connect()
         android.folder_select("Upload")
         android.ftp_localfolder()
         adbClient.adb_event("123")
         adbClient.adb_event("123")
         android.folder_select("Upload")
         android.ftp_upload(filename)
         adbClient.Transfer_Status(filestart, fileend)
         adbClient.getfile_command()
         adbClient.Check_FileStatus()
         adbClient.adb_event("4")
         android.screen_shot_save("FTP_Upload")
         adbClient.FTP_Urate()
         adbClient.adb_event("66")
         adbClient.adb_event("66")
         adbClient.adb_event("111")
         adbClient.adb_event("111")
         adbClient.adb_event("111")
     android.mobile_device_disconnect()
Ejemplo n.º 31
0
from android import Android
import time

droid = Android()

defH = int(input('Hora (0-23): '))
defM = int(input('Minuto (0-59): '))
texto = input('Texto ("despierta"): ')

while True:
    h = int(time.strftime('%H'))
    m = int(time.strftime('%M'))
    if (h == defH and m >= defM):
        droid.ttsSpeak(texto)
        print(texto)
    time.sleep(10)
Ejemplo n.º 32
0
 def iperf_AN(self):
     android = Android()
     adbClient = AdbClient()
     adbClient.swiandroidh_iperf()
     iperf_command = "-s -i -5"
     android.mobile_device_connect()
     android.service_iperf_start(iperf_command)
     android.iperf_log_clean()
     adbClient.client_iperf_start()
     adbClient.adb_event("4")
     android.screen_shot_save(iperf_command)
     android.mobile_device_disconnect()
     adbClient.move_file("Down_androidP_")
Ejemplo n.º 33
0
#importamos las librerias que utiliza la aplicación
import sys
import math
import time

#el siguiente coduigo es escencial para que el dialogCreateAlert funcione
from android import Android
droid = Android()

#Primera llamada de la aplicacion con el interprete de android
mensaje1 = 'Hola, me llamo Contador, y te dire cuanto te mueves en 30 segundos'
droid.ttsSpeak(mensaje1)

# tiempo de espera en segundos para ejecucion del siguiente codigo
time.sleep(5)

#Mensaje de dialogo
droid.dialogCreateAlert('Cuenta pasos', '¿Listo para iniciar?')

droid.dialogSetPositiveButtonText('Si')
droid.dialogSetNegativeButtonText('No')

droid.dialogShow()

#dependiendo de la respuesta escogida en el dialogo será el resultado, si es no la opcion escogida se despide el interprete y
#se finaliza la aplicacion, si es si inicia la aplicacion para contar los pasos aproximados en 8 segundos

response = droid.dialogGetResponse().result
droid.dialogDismiss()

if not 'which' in response or response['which'] != 'positive':
Ejemplo n.º 34
0
	import json
	import time
	from android import Android
	
	droid = Android()
	# dt = 100ms
	dt = 0.1
	droid.startSensingTimed(1, dt)
	droid.webViewShow('file:///sdcard/sl4a/scripts' +
	                  '/SensorGraph/Accelerometer/accUI.html')
	xList = [0] * 20
	yList = [0] * 20
	zList = [0] * 20
	
	def postAccelerometerValues():
	    xyzList = droid.sensorsReadAccelerometer().result
	
	    xList.append(xyzList[0])
	    yList.append(xyzList[1])
	    zList.append(xyzList[2])
	
	    del xList[0]
	    del yList[0]
	    del zList[0]
	
	    xyzDict = {"x":xList, "y":yList, "z":zList}
	    droid.eventPost('stdout', json.dumps(xyzDict))
	
	while True:
	    postAccelerometerValues()
	    time.sleep(0.3)
Ejemplo n.º 35
0
"""
    Use with Scripting Layer for Android (SL4A).
"""
from android import Android
from endecryptor import EnDecryptor

# Instantiate our main classes.
droid = Android()
endec = EnDecryptor()

def get_user_mode():
    """Asks the user whether to use Encrypt or Decrypt mode."""
    droid.dialogCreateAlert("Set Application Mode")
    droid.dialogSetItems(["Encrypt", "Decrypt"])
    droid.dialogShow()
    if droid.dialogGetResponse().result["item"] == 1:
        return False, "decrypt"
    else:
        return True, "encrypt"

def show_user_result(result_string):
    """Shows the user the result of the encryption/decryption process and
    lets the user save that result onto the clipboard for later use.
    """
    droid.dialogCreateAlert("Endecryptor Result", result_string)
    droid.dialogSetPositiveButton("Copy")
    droid.dialogSetNegativeButton("Exit")
    droid.dialogShow()
    if droid.dialogGetResponse().result["which"] == "positive":
        droid.setClipboard(result_string)
        droid.makeToast("Copied to Clipboard.")
Ejemplo n.º 36
0
import sys
 
from android import Android
droid = Android()
 
droid.webViewShow('/sdcard/com.hipipal.qpyplus/projects3/SEAS/webgui/gui.html')


# Complete one iteration for each event
while True: 
    event = droid.eventWait().result
    
    #if event['name'] == 'ttsaction':
    droid.ttsSpeech(event["data"])
Ejemplo n.º 37
0
from android import Android
import time

droid = Android()

scanStarted = droid.wifiStartScan()
print(scanStarted)
Ejemplo n.º 38
0
def compile(c):
    global project_dir
    global sdk_dir
    global deploy_type
    global builder
    global android
    global config
    global template_dir
    global jar_dir
    global restore_performed
    global classpath_separator
    global moduleAvailable
    global touchtest_module_dir_created

    print "[DEBUG] TouchTest : %s" % c

    config = c

    # This Plugin is only for the Android platform.
    if config['platform'] != 'android':
        return

    moduleAvailable = isAndroidModuleEnabled(
        config['tiapp'].properties['modules'], config['deploy_type'])
    touchtest_module_dir_created = []

    if moduleAvailable:
        from android import Android
        from compiler import Compiler

        # Initialize variables
        project_dir = config['project_dir']
        sdk_dir = config['titanium_dir']
        deploy_type = config['deploy_type']
        template_dir = config['template_dir']
        jar_dir = project_dir + "/plugins/com.soasta.touchtest.android/lib/"

        # Initialize the restore_performed value to be False
        restore_performed = False

        # Initialize classpath
        builder = config['android_builder']
        android = Android(builder.name, builder.app_id, builder.sdk, 'test',
                          builder.java)
        full_resource_dir = os.path.join(
            builder.project_dir, builder.project_dir + "/bin/assets/Resources")
        compiler = Compiler(config['tiapp'],
                            full_resource_dir,
                            builder.java,
                            project_dir + "/bin/Classes",
                            builder.project_gen_dir,
                            project_dir,
                            include_all_modules=True)
        classpath = os.pathsep.join([
            builder.sdk.get_android_jar(),
            os.pathsep.join(compiler.jar_libraries)
        ])

        # Classpath separator on Windows is a semi-colon instead of a colon
        classpath_separator = ":"
        if (os.name == 'nt'):
            classpath_separator = ";"

        module_jars = findAndroidModuleJars(
            config['tiapp'].properties['modules'])

        classpath = classpath + classpath_separator + jar_dir + "aspectjrt.jar"
        classpath = classpath + classpath_separator + jar_dir + "aspectjtools.jar"

        for module_jar in module_jars:
            print "[INFO] TouchTest : Will also process %s" % module_jar
            classpath = classpath + classpath_separator + module_jar

        print "[INFO] TouchTest : Installing TouchTest Driver for Android"

        print "[DEBUG] TouchTest : Preparing libraries"
        print "[DEBUG] TouchTest : Using classpath %s" % classpath

        createBackup("titanium")
        createBackup("modules/titanium-ui")

        step = 0
        try:
            step = 1
            instrument(classpath, "titanium")
            step = 2
            instrument(classpath, "modules/titanium-ui")
            step = 3
            for module_jar in module_jars:
                instrumentExternalJars(classpath, module_jar)

            merge()
            print "[INFO] TouchTest : TouchTest Driver for Android installed"

        except:
            print "[ERROR] TouchTest : Unexpected error:", sys.exc_info(
            )[0], sys.exc_info()[1], sys.exc_info()[2], "- step ", str(step)
            print "[ERROR] TouchTest : Exception occured. Restoring Titanium jar files."
            restore("titanium")
            restore("modules/titanium-ui")
            print "[ERROR] TouchTest : TouchTest Driver was not installed."
Ejemplo n.º 39
0
from android import Android
import time,sys
 
droid = Android()
droid.webViewShow('file:///sdcard/sl4a/scripts/daveTest/index.html')
 
# Complete one iteration for each event
while True: 
    event = droid.eventWait().result
    
    if event['name'] == 'kill':
        sys.exit()
    elif event['name'] == 'bluetooth':
	droid.toggleBluetoothState(True)
	droid.bluetoothConnect()
	while True:
	  message = droid.bluetoothReadLine().result
	  droid.eventPost('bluetoothOut', message)
	  if message =='quit':
	    title = 'dvas0004'
	    text = 'Server told me to turn bluetooth off'
            droid.dialogCreateAlert(title, text)
	    droid.dialogSetNeutralButtonText('Ok')
            droid.dialogShow()
            droid.dialogGetResponse().result
            droid.dialogDismiss()
	    break

    elif event['name'] == 'sayHi':

        droid.notify('dvas0004',event['data'])
Ejemplo n.º 40
0
def get_gps():
    android = Android()
    while True:
        main.loc = android.getLatAndLon()     
from android import Android
import subprocess
import datetime
import time

limit = 90

a = Android()

print("starting monitor funcs")
a.batteryStartMonitoring()
time.sleep(1)
print("monitoring engaged, waiting for battery level to be full")
while not a.batteryGetStatus().result == 5:
    time.sleep(0.5)
print("battery full, unplug now")
while a.batteryGetStatus().result == 5:
    time.sleep(0.1)

print(subprocess.check_output(["dumpsys", "batterystats", "--reset"]))

print("Time: " + str(datetime.datetime.now()))
print("Battery level: " + str(a.batteryGetLevel().result))

counter = 1
while a.batteryGetLevel().result > limit:
    time.sleep(1)
    counter = counter + 1
    if (counter > 10):
        counter = 0
        with open("/sdcard/voltages.txt", "a") as file:
Ejemplo n.º 42
0
import json
import time
from android import Android

droid = Android()
# dt = 100ms
dt = 0.1
droid.startSensingTimed(1, dt)
droid.webViewShow('file:///sdcard/sl4a/scripts' +
                  '/SensorGraph/Magnetometer/magUI.html')
xList = [0] * 20
yList = [0] * 20
zList = [0] * 20

def postMagnetometerValues():
    xyzList = droid.sensorsReadMagnetometer().result

    xList.append(xyzList[0])
    yList.append(xyzList[1])
    zList.append(xyzList[2])

    del xList[0]
    del yList[0]
    del zList[0]

    xyzDict = {"x":xList, "y":yList, "z":zList}
    droid.eventPost('stdout', json.dumps(xyzDict))

while True:
    postMagnetometerValues()
    time.sleep(0.3)