def stopapp(actvy): droid = android.Android() i = actvy.rfind('.') if i > 0: pkg = actvy[:i] droid = android.Android() respond = droid.forceStopPackage(pkg) print respond return template(PAGE_TEMP % ('', 'done'))
def time_compare(hr,min,sec,msec): droid = androidhelper.Android() now_time = datetime.datetime.now() print('present time is :',now_time) cusertime = now_time.replace(hour=hr,minute=min,second=sec,microsecond=msec) print(red+"made by your current time,your current time is : "+end,cusertime) morning0 = now_time.replace(hour=0,minute=0,second=1,microsecond=1) morning3 = now_time.replace(hour=3,minute=0,second=0,microsecond=0) morning6 = now_time.replace(hour=6,minute=0,second=0,microsecond=0) noon12 = now_time.replace(hour=12,minute=0,second=1,microsecond=1) evening5 = now_time.replace(hour=16,minute=0,second=0,microsecond=0) night8 = now_time.replace(hour=20,minute=0,second=0,microsecond=0) try: if morning3 <= cusertime < morning6: print("oohh sayantan it's soo early morning. what is the work now ?") droid.ttsSpeak("oh sayantan it's so early morning. what is the work now ?") elif morning6 <= cusertime < noon12: print('good morning sayantan') droid.ttsSpeak('good morning sayantan') elif noon12 <= cusertime < evening5: print('good afternoon sayantan') droid.ttsSpeak("good afternoon sayantan") elif evening5 <= cusertime < night8: print('good evening sayantan') droid.ttsSpeak('good evening sayantan !') elif morning0 <= cusertime < morning3: print(ylo+"hey sayantan ! what r you doing at deep night ?, I suggest you to go and get a sleep"+end) droid.ttsSpeak("hey sayantan ! what r you doing at deep night ?, I suggest you to go and get a sleep") else: print('I can see my bed, I want to sleep') droid.ttsSpeak('I can see my bed, I want to sleep') except exception as e: print('Error found')
def __init__(self): global byte global lastbyte global ser # Variablen fuer die Messwerte vom Feinstaubsensor. byte, lastbyte = "\x00", "\x00" threading.Thread.__init__(self) if android_platform: self.droid = androidhelper.Android() self.connID = None else: # Hier wird auf den Serial-USB Konverter zugegriffen try: ser = serial.Serial(sds011, baudrate=9600, stopbits=1, parity="N", timeout=2) except Exception, e: write_log("\n HL-340 USB-Serial Adapter nicht verfuegbar. \n" + str(e)) try: ser.flushInput() except Exception, e: write_log(e)
def camerababy(): import androidhelper droid = androidhelper.Android() if not exists(ROOT + '/photo'): photoid = 1 os.makedirs(ROOT + '/photo') else: photoid = sum( [len(files) for root, dirs, files in os.walk(ROOT + '/photo')]) + 1 # 设置照片名 photoname = str('babyrecordphoto%d.jpg' % photoid) # 拍照 droid.cameraInteractiveCapturePicture(ROOT + '/photo/%s' % photoname) # 保存照片名 nowtime = time.strftime("%d/%m/%Y %H:%M:%S") data = nowtime, photoname savephotoname(data) # 读取照片名 namelist = readphotoname() return template(camerahtml, indexhtml=indexhtml, historyhtml=historyhtml, babyhtml=babyhtml, emailhtml=emailhtml, camerahtml=camerahtml, photoid=photoid, photoname=namelist)
def get_data(): print "trying to retrieve from clipboard" try: import androidhelper android = androidhelper.Android() return android.getClipboard().result except ImportError: return sys.argv[1]
def api_run(): path = PROJ_ROOT+'/'+request.POST.get('path') try: import androidhelper droid = androidhelper.Android() droid.executeQPy(path) except: return 'err' return 'ok'
def home(): droid = android.Android() respond = droid.getLaunchableApplications() JS = "" CONTENT = u''.join([ u'<div>{0}: {1} <a href="/startapp/{1}">Start</a> <a href="/stopapp/{1}">Stop</a></div>' .format(k, v) for k, v in respond.result.items() ]) return template(PAGE_TEMP % (JS, CONTENT))
def startapp(actvy): i = actvy.rfind('.') if i > 0: pkg = actvy[:i] droid = android.Android() respond = droid.startActivity('android.intent.action.MAIN', packagename=pkg, classname=actvy) print respond return template(PAGE_TEMP % ('', 'done'))
def api_run(): response.headers['Access-Control-Allow-Origin'] = '*' path = PROJ_ROOT + '/' + request.POST.get('path') try: import androidhelper droid = androidhelper.Android() droid.executeQPy(path) except: return 'err' return 'ok'
def testtime(): droid = androidhelper.Android() droid.makeToast("Current Time recived") user_time = (time.strftime("%H:%M:%S:00")) #user_time = input("Enter the time value \n\n") hr,min,sec,msec = str(user_time).split(':') print(hr,min,sec,msec,type(user_time)) print('_'*40) time_compare(hr=int(hr),min=int(min),sec = int(sec),msec=int(msec))
def __init__(self): self.droid = androidhelper.Android() settings = XMPPSettings({"software_name": "Say Chat"}) settings["jid"] = self.droid.dialogGetInput( "Google Talk Username").result settings["password"] = self.droid.dialogGetInput( "Google Talk Password").result settings["server"] = "talk.google.com" settings["starttls"] = True self.client = Client(JID(settings["jid"]), [self, VersionProvider(settings)], settings)
def __init__(self): global session global g_lat, g_lng, g_utc threading.Thread.__init__(self) self.droid = androidhelper.Android() self.droid.startLocating(5000, 10) g_lat, g_lng = self.getGpsData() g_utc = datetime.datetime.utcnow() self.current_value = None # Der Thread wird ausgefuehrt self.running = True
def createDroid(): for i in range(3): try: global droid droid = androidhelper.Android() return except: pass print 'Error encurred during init operation \n Please restart application.' print 'If the problem persist \n Try kill and reopen QPython interpreter' print 'Finally \n Please restart your device' quit()
def main(): """Old CLI.""" if len(sys.argv) < 2: # maybe phone clipboard try: import androidhelper print("trying to retrieve from clipboard") except ImportError: return usage() # go to the right location try: os.chdir('/mnt/sdcard/Download') except OSError: pass the_url = androidhelper.Android().getClipboard().result command = 'dl' elif len(sys.argv) == 4: command = sys.argv[1] the_url = sys.argv[2] query = sys.argv[3] elif len(sys.argv) == 3: command = sys.argv[1] the_url = sys.argv[2] else: command = 'dl' the_url = sys.argv[1] if command == 'dl': command_dl(the_url) elif command == 'ls': command_ls(the_url) elif command == 'find': command_find(the_url, query) elif command == 'play': command_play(the_url) elif command == 'shell': command_shell(the_url) elif command == 'rdl': command_rdl(the_url) elif command == 'rls': try: command_rls(the_url) except KeyboardInterrupt: pass if len(interesting): print('%d Interesting folders:' % len(interesting)) for ifolder in interesting: print(ifolder) else: print("Error: unknown command %s." % command) return usage()
def countdown_timer(): times = 10 os.system('clear') #times = int(input("Enter times of count down: ")) i = 1 #while(i !=""): for i in range(times): droid = androidhelper.Android() print(str(times-i),cyan+"\t","time remain"+end) timer = (str(times-i)) droid.ttsSpeak(timer) time.sleep(1) i = (i-1)
def __init__(self, android): super(GestureRecogniser, self).__init__() if android == True: try: import androidhelper as android except: import android global droid droid = android.Android() droid.startSensingTimed(1, 100) self.android_use = True else: self.android_use = False
def serialStart(): '''ArduinoとAndroidのシリアル通信''' droid = android.Android() enable = droid.usbserialHostEnable() l = droid.usbserialGetDeviceList().result.items() tk = str(l).split(',')[-1] h = tk.split(chr(34))[1] ret = droid.usbserialConnect(str(h)) uuid = str(ret.result.split(chr(34))[-2]) print('uuid: ', uuid) time.sleep(3) active = droid.usbserialActiveConnections() print('active: ', active) return droid, uuid
def __init__(self): global byte global lastbyte global ser # Variablen fuer die Messwerte vom Feinstaubsensor. byte, lastbyte = "\x00", "\x00" threading.Thread.__init__(self) self.droid = androidhelper.Android() self.connID = None self.current_value = None # Der Thread wird ausgefuehrt self.running = True
def __init__(self): global session global g_lat, g_lng, g_utc threading.Thread.__init__(self) if android_platform: self.droid = androidhelper.Android() self.droid.startLocating(5000, 10) g_lat, g_lng = self.getGpsData() g_utc = datetime.datetime.utcnow() else: session = gps(mode=WATCH_ENABLE) g_utc = session.utc g_lat = session.fix.latitude g_lng = session.fix.longitude self.current_value = None # Der Thread wird ausgefuehrt self.running = True
def android_args(): try: import androidhelper as android except ImportError: import android protocols = ['TCP', 'UDP', 'ICMP'] host = None port = None droid = android.Android() droid.dialogCreateInput(title='Destination Host', message='Hostname or IP', inputType='text') droid.dialogSetPositiveButtonText('OK') droid.dialogShow() host = droid.dialogGetResponse().result['value'] droid.dialogCreateAlert(title='Protocol', message='Choose the traceroute protocol') droid.dialogSetSingleChoiceItems(protocols) droid.dialogSetPositiveButtonText('OK') droid.dialogShow() proceed = droid.dialogGetResponse().result['which'] protoindex = droid.dialogGetSelectedItems().result[0] if protoindex != 2: droid.dialogCreateInput(title='Port Number', message='Port', inputType='number', defaultText='80') droid.dialogSetPositiveButtonText('OK') droid.dialogShow() port = droid.dialogGetResponse().result['value'] else: port = '' proto = protocols[protoindex].lower() results = [] if proto in ["icmp", "udp"]: results.append("--" + proto) if proto != "icmp": results.extend(["--port", port]) results.append(host) return results
def _dialog(title, flist): '''display dialog with list of files/folders title allowing user to select any item or click Cancel get user input and return selected index or None ''' import androidhelper droid = androidhelper.Android() droid.dialogCreateAlert(title, '') droid.dialogSetItems(flist) droid.dialogSetNegativeButtonText('Cancel') droid.dialogShow() resp = droid.dialogGetResponse() droid.dialogDismiss() print resp if resp.result.has_key('item'): print 'RETURN:', resp.result['item'] return resp.result['item'] else: return None
def __init__(self): if sys.platform == 'linux-armv7l': import androidhelper self._droid = androidhelper.Android() self._droid.startLocating() os.chdir('/storage/emulated/0/qpython') else: #Mock gps call class MockDroid: def getLatestLocation(self): return def readLocation(self): class Result: result = {'gps': {'latitude': 1, 'longitude': 2}} return Result() self._droid = MockDroid()
def ins_n_imp_voice(): global not_installed NoVoiceError = "\n \n|*Warning! Voice won't work\n\033*|" if os_name() == 'Windows': try: if not check_installed('pywin32'): install('pywin32') ins_n_imp('pyttsx3') vmodule = 'pyttsx3' global engine if check_installed('pyttsx3') == True: engine = pyttsx3.init() # Set properties _before_ you add things to say engine.setProperty('rate', 190) # Speed percent (can go over 100) engine.setProperty('volume', 0.1) # Volume 0-1 en_voice_id = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0" # Use female English voice engine.setProperty('voice', en_voice_id) else: raise ValueError except ValueError: ins_frm_imp('gtts', 'gTTS') if check_installed('gtts') == True: vmodule = 'gtts' else: print(NoVoiceError) vmodule = 'unav' elif os_name == 'linux': try: import androidhelper global droid droid = androidhelper.Android() vmodule = 'androidhelper' except: vmodule = 'unav' else: vmodule = 'unav' droid = None return vmodule
def on_message(client, userdata, message): mess = message.payload.decode('utf-8') print(mess) mobid = 'jasmine' if mess[0] == 'm': msg = 'false' print("entered") while (msg != 'true'): print("entered") droid1 = androidhelper.Android() droid1.dialogGetPassword("please enter your password", "Confirm your identity") result = droid1.dialogGetResponse().result ans = result.get("value") print(ans) mobid = 'jasmine' if (ans == mobid): msg = 'true' publish.single('result', msg, qos=2, hostname='m16.cloudmqtt.com', port=17679, auth={ 'username': '******', 'password': '******' }) client.disconnect() client.loop_stop() publish.single('result', 'true', qos=2, hostname='m16.cloudmqtt.com', port=17679, auth={ 'username': '******', 'password': '******' }) client.disconnect() client.loop_stop()
#-*-coding:utf8;-*- ch = "@special_programming" import telebot API_TOKEN = '288894414:AAEIdvaPN-I8DSlcXw7RIosjkGdUw84y0mc' bot = telebot.TeleBot(API_TOKEN) import androidhelper droid = androidhelper.Android() line = droid.dialogGetInput("please enter your text with markdown") s = "%s" % (line.result,) droid.makeToast(s) bot.send_message(ch, "{}".format(s), parse_mode="Markdown", disable_web_page_preview=True)
try: import androidhelper as android except ImportError: try: import android except: ANDROID = False try: import bluetooth except: exit() if ANDROID == True: global droid droid = android.Android() class Interface(BoxLayout): def connect(self): try: droid.toggleBluetoothState(True) droid.bluetoothMakeDiscoverable(4000) self.conn = droid.bluetoothAccept() droid.makeToast('Connection made with {0}'.format( self.conn.result)) except: pass def send(self): try:
def platform_init(emu): emu.myId = format(int(hostid(), 16) & 0xffffff, 'x') emu.droid = androidhelper.Android() emu.droid.startLocating(1000, 0)
def escute(self): droid = android.Android() (id, result, error) = droid.recognizeSpeech("Fale") return result # Retorna uma string com o que foi ouvido
import androidhelper app = androidhelper.Android() app.makeToast("hello qpython")
def main(): subprocess.Popen('su', shell=True) # change to root user subprocess.Popen('echo $(tty); cat /dev/ttyACM0 > $(tty) &', shell=True) # show AT responses - not working # client constants UDP_IP = "152.66.130.2" # ural2.hszk.bme.hu UDP_PORT = 5005 MESSAGE = '' # sensing constants NUMBER_OF_UPDATES = 22 TIME_BETWEEN_UPDATES = 12 # sec PRECISION = 3 path = '/storage/emulated/0/qpython/test/' data_path = os.path.join(path, 'local_data.txt') os.chdir(path) if os.path.isfile(data_path): os.remove(data_path) # start monitoring droid = androidhelper.Android() droid.batteryStartMonitoring() droid.startSensingTimed( 1, 250) # 1: all sensors, 250: minimum time between readings droid.wakeLockAcquirePartial( ) # run for a long time even when screen is off for i in range(NUMBER_OF_UPDATES): time.sleep(TIME_BETWEEN_UPDATES) # get sensor data orient = droid.sensorsReadOrientation().result accel = droid.sensorsReadAccelerometer().result magneto = droid.sensorsReadMagnetometer().result light = droid.sensorsGetLight().result battery = droid.batteryGetLevel().result sensors_data_list = [orient, accel, magneto, [light], [battery]] print('Saving data...') with open(data_path, 'a') as f: LIST = [] for sensor_data in sensors_data_list: sensor_data_list = [] for result_value in sensor_data: truncated = '{0:.{1}f}'.format(result_value, PRECISION) sensor_data_list.append(truncated + ' ') LIST.append(''.join(sensor_data_list)) # string LIST = ''.join(LIST) if len(LIST) % 2 == 1: # pad odd length string for encoding LIST += ' ' #udp_send(LIST) # testing nb_send(LIST) f.write(LIST) f.write('\n#\n') # stop monitoring droid.batteryStopMonitoring() droid.stopSensing() droid.wakeLockRelease() time.sleep(1)