Monkeyrunner. Connect to multiple devices at the same time - monkeyrunner

I used this script to connect to multiple Android devices at the same time (i.e. to send files via adb):
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
import time
import sys
import time
import os
devices = os.popen('adb devices').read().strip().split('\n')[1:]
device1 = MonkeyRunner.waitForConnection( devices[0].split('\t')[0])
package = 'com.android.browser'
activity = 'com.android.browser.BrowserActivity'
runComponent = package + '/' + activity
device1.startActivity(component=runComponent)
MonkeyRunner.sleep(1)
device2 = MonkeyRunner.waitForConnection( devices[1].split('\t')[0])
package = 'com.android.browser'
activity = 'com.android.browser.BrowserActivity'
runComponent = package + '/' + activity
device2.startActivity(component=runComponent)
I used
adb 1.0.36 (Rev 1:7.0.0+r33-2) and
monkyrunner(Jython 2.5.3 (2.5:c56500f08d34+, Aug 13 2012, 14:54:35)
But all I get is:
09:02:54 E/DeviceMonitor: Adb connection Error:EOF
09:02:54 E/DeviceMonitor: Connection attempts: 1
09:02:55 E/DeviceMonitor: Connection attempts: 2
09:02:56 E/DeviceMonitor: Connection attempts: 3
Any hints what to do?
Thanks!
(Original Thread: How to run Monkeyrunner script on multiple devices at the same time )

You can use AndroidViewClient/culebra which supports multiple devices. If I recall correctly, this was one of the limitations of monkeyrunner that AndroidViewClient solved.
You can simply generate the script using
$ culebra -Uu --multi-device --start-activity='com.android.chrome/com.google.android.apps.chrome.Main' -o multi-browser.py
which generates a unit test (-U), does not verify what's in the screen dump (-u), use multiple devices, starts a specific activity as a precondition and saves the generated script to multi-device.py.
Then, run the script as
$ multi-browser.py -s all
where -s specifies the serial numbers of the devices where you want the script to run, all in this case, and the browser will start on all of them.

Related

How can I save VoD recordings without stopping streaming?

How can I stop recording intervally without stopping the stream to save the VoD in Ant Media Server in my stream sources and IP cameras?
You can achieve that with a python script. Assuming you have installed python3 and pip.
Following script stops and starts the recording again in user-defined intervals:
import sys
import sched, time
try:
import requests
print("requests library already installed!")
except ImportError:
try:
import pip
print("requests library is being installed")
pip.main(['install', '--user', 'requests'])
import requests
except ImportError:
print("pip is not installed, so it needs to be installed first to proceed further.\nYou can install pip with the following command:\nsudo apt install python3-pip")
slp=sched.scheduler(time.time,time.sleep)
def startStopRecording(s):
print("Stopping the recording of "+sys.argv[2])
response=requests.put(sys.argv[1]+"/rest/v2/broadcasts/"+sys.argv[2]+"/recording/false")
if response.json()["success"]:
print("recording of "+sys.argv[2]+" stopped successfully")
print(response.content)
print("starting the recording of "+sys.argv[2])
response=requests.put(sys.argv[1]+"/rest/v2/broadcasts/"+sys.argv[2]+"/recording/true")
print(response.content)
if response.json()["success"]:
print("recording of "+sys.argv[2]+" started successfully")
s.enter(int(sys.argv[3]),1,startStopRecording,(s,))
else:
print("Couldn't start the recording of "+sys.argv[2])
print("content of the response:\n"+response.content)
sys.exit()
else:
print("Couldn't stop the recording of "+sys.argv[2])
print("content of the response:")
print(response.content)
sys.exit()
slp.enter(int(sys.argv[3]),1,startStopRecording,(slp,))
slp.run()
Example usage would be like: python3 file.py https://domain/{Application} streamId interval
First parameter is the domain you are going to use like: https://someexample.com:5443/WebRTCAppEE
Second parameter is the stream id you want to use. Ex. stream123.
Third parameter is the duration of the interval you want to restart the recording. Duration unit is seconds. So 60 would be equal to 1 minute.

USB VCP Acces denied with pySerial

I just put my hand on a OpenMV Cam H7 Plus that is using micro-python. I am trying an example that is supposed to take a python program to ask for a picture from the camera and save it. As far as I understand (still new to python) is the camera IDE creates a virtual serial port and listens for a command. The main python program try to open the port (COM4) and is denied. The problem , I think, is the port is already in use. How can I get access?
IDE micro-python code
import sensor, image, time, ustruct
from pyb import USB_VCP
usb = USB_VCP()
sensor.reset() # Reset and initialize the sensor.
sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240)
sensor.skip_frames(time = 2000) # Wait for settings take effect.
print("USB is a Com Port", usb.isconnected())
while(True):
cmd = usb.recv(4, timeout=5000)
if (cmd == b'snap'):
img = sensor.snapshot().compress()
usb.send(ustruct.pack("<L", img.size()))
usb.send(img)
Main python Code
import serial
import struct
port = 'COM4'
sp = serial.Serial(port, baudrate=115200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE,
xonxoff=False, rtscts=False, stopbits=serial.STOPBITS_ONE, timeout=None, dsrdtr=True)
sp.setDTR(True) # dsrdtr is ignored on Windows.
sp.write("snap")
sp.flush()
size = struct.unpack('<L', sp.read(4))[0]
img = sp.read(size)
sp.close()
with open("img.jpg", "w") as f:
f.write(img)
And in running the main i get the error:
File "C:\Users\Vincent\usbpcvtest\lib\site-packages\serial\serialwin32.py", line 62, in open
raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM4': PermissionError(13, 'Access is denied.', None, 5)
I find out how it works. The Cam auto-run the main.py when you initialize the port with a program on another computer. So all i had to do is renamed my IDE micro-python code "main.py" and to put it in the root of the cam.
the only bug is if you start the IDE you need to reconnect the cam physicaly so that the cam boot the main.py before you start your program on the main computer.

Using Apache Airflow Tool, Implement a DAG for a batch processing pipeline to get a directory from a remote system

Using Apache airflow tool, how can I implement a DAG for the following Python code. The task accomplished in the code is to get a directory from GPU server to local system. Code is working fine in Jupyter notebook. Please help to implement in Airflow...I'm very new to this. Thanks.
import pysftp
import os
myHostname = "hostname"
myUsername = "username"
myPassword = "pwd"
with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword) as sftp:
print("Connection successfully stablished ... ")
src = '/path/src/'
dst = '/home/path/path/destination'
os.mkdir(dst)
sftp.get_d(src, dst, preserve_mtime=True)
print("Fetched source images from GPU server to local directory")
# connection closed automatically at the end of the with-block```
For SFTP duties, Airflow provides SFTOperator that you can use directly.
Alternatively it's corresponding SFTPHook can be used with a simple PythonOperator
I acknowledge there aren't many examples, but this might be helpful
For SSH-connection, see this

E-mail (or similar) notification when code execution is finished

I am currently doing several simulations in R that each take quite a long time to execute and the time it takes for each to finish varies from case to case. To use the time in between more efficiently, I wondered if it would be possible to set up something (like a e-mail notification system or similar) that would notify me as soon a a chunk of simulation is completed.
Does somebody here have any experience with setting up something similar or does someone know a resource that could teach me to implement a notification system via R?
I recently saw an R package for this kind of thing: pushoverr. However didn't use it myself - so not tested how it works. But seems like it might be useful in your case.
I assume you run the time consuming simulations on a server, correct? If these run own you own PC, your PC will be slow as hell anyway and I would not see something beneficial in sending a mail to myself.
For long calculations: Run them on a virtual machine, I use the following workflow for my own calculations.
Write your R script. Important: Write a .txt file when the calculation file in the end. The shell script will search in a loop for the file to exist.
Copy that code an save it as Python script. I tried one day to get MailR running a Linux and it did not work. This code worked on the first try.
#!/usr/bin/env python3
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
email_user = 'youownmail#gmail.com'
email_password = 'password'
email_send = 'theothersmail.com'
subject = 'yourreport'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = 'Calculation is done'
msg.attach(MIMEText(body,'plain'))
part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
msg.attach(part)
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(email_user,email_password)
server.sendmail(email_user,email_send,text)
server.quit()
Make sure you are allowed to run the script.
sudo chmod 777 /path/script.R sudo chmod 777 /path/script.py
Run both your script.R and script.py inside a script.sh file. It looks the the following:
R < /path/script.R --no-save
while [ ! -f /tmp/finished.txt ]
do
sleep 2
done
python path/script.py
This may sound a bit overwhelming if you are not familiar with these technologies, but think this is a pretty much automated workflow, which relieves your own resources and can be used "in production". (I use this workflow to send me my own stock reports).

How to run from the real device monkeyrunner script?

I have written this code which is working in the emualator. How do I get it to work in a real device? Is just connecting the device and changing the location (device location of apk) enough?
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
# Connect to the current device
device = MonkeyRunner.waitForConnection()
# Install package
device.installPackage('C:/android-sdk-windows/tools/lib/purchase.apk')
# Run activity
device.startActivity(component='com.mobilenetwork.purchase/.StartPage ')
# Importing time
import time
# Waiting for 10 secs to be launched on the emulator:
time.sleep(10)
device.press('KEYCODE_BUTTON_SELECT','DOWN','')
# Screenshot
time.sleep(10)
result = device.takeSnapshot()
# Writes the screenshot to a file
result.writeToFile('G:\\Screenshot\\screen_shot.png','png')
This looks like it should work on a real device just the way it is right now. If you are experiencing issues, you might want to try adding "MonkeyRunner.sleep(n)" (where n is a number) statements. Some devices do not wait for the last task to finish before asking for the next one.
You might also try configuring the package and activity before you connect to the device.

Resources