[SL4A] running sl4a script don't put back phone to sleep - Android Software Development

Hi,
I have a problem of draining battery with SL4A.
First, what i do :
I use Tasker to run SL4A script during night. I repeat script all 10 min. The script give back phone orientation to tasker. if phone don't move during 30min, i put phone in airplane mode and stop to repeat script all 10 min. I do this action only if screen is off, so phone in sleep mode.
The battery draining don't come from tasker, i test it without run SL4A script, no problem. I sure it's because of SL4A.
So with this script, i get battery drain during all night, and battery drain stop when alarm ring on morning (so when phone awake, it's important, remind this)
My script is this one :
Code:
import android, time
droid = android.Android()
class Task():
SET_VARIABLE = 547
def new_task(self):
self.action_cnt = 0
self.extras = {'version_number': '1.0', 'task_name': 'task' + str(time.time()), 'task_priority': 10 }
def set_var(self, varname, value):
self.action_cnt += 1
self.extras['action' + str(self.action_cnt)] = {'action': self.SET_VARIABLE, 'arg:1': varname, 'arg:2': value, 'arg:3': False, 'arg:4': False, 'arg:5': False}
def run_task(self):
taskIntent = droid.makeIntent('net.dinglisch.android.tasker.ACTION_TASK', None, None, self.extras).result
droid.sendBroadcastIntent(taskIntent)
def set_var_now(self, varname, value):
self.new_task()
self.set_var(varname, value)
self.run_task()
temps = 20
droid.startSensingTimed(1,500)
while temps > 0:
time.sleep(0.5)
x, y, z = droid.sensorsReadOrientation().result
temps = temps - 1
if x is not None:
break
droid.stopSensing()
t = Task()
t.new_task()
if x is not None:
t.set_var("%ORIENTATION_X", str(x))
t.set_var("%ORIENTATION_Y", str(y))
t.set_var("%ORIENTATION_Z", str(z))
t.set_var("%ORIENTATION", "Done")
t.run_task()
What i do in this script :
I read orientation (max 20 time in case of none result) and i send information to tasker.
I d'ont think i do error in this script.
So i think SL4A don't allow phone to back to sleep mode after finished is script.
Because i find a solution, turn on screen during one second after running script (i do this in tasker) and now, i don't have battery drain.
But this solution is not clean.
Any help to solve this problem ?
thanks a lot

I''m still kinda new to java coding but I really think you need to reffer to:
PARTIAL_WAKE_LOCK
like this:
Code:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
//WAIT here
wl.acquire();
// action here
wl.release();
full reference:
http://developer.android.com/reference/android/os/PowerManager.html
releases the wake lock after the process is finished. I hope that that info is correct, as im note sure.

Have you tried running your script on the emulator to make sure it's exiting properly?
I'm a bit worried about while code (python or not).
Sent from my HTC One X using xda premium

My code work properly, no error in console. Code is in Python (i'm not specialist but if i understand well, the "wend" is do by indentation)
And if code have error, turn on screen 1s after script will don't have any effect, i thinks.
About power management: after read, it's can be this problem. May be if do my own wake lock, SL4A will do one automatically (and forgot to close it)
I will try.

I don't arrive to get powerManager function :crying:
i try to add
Code:
pm = droid.powerManager()
pm.goToSleep(droid.sytemClock.uptimeMillis())
but no way goToSleep function is unknow.
Some help for syntax, i don't find any example. Thanks

i do like this
Code:
import android, time
droid = android.Android()
droid.wakeLockAcquirePartial()
class Task():
SET_VARIABLE = 547
def new_task(self):
self.action_cnt = 0
self.extras = {'version_number': '1.0', 'task_name': 'task' + str(time.time()), 'task_priority': 10 }
def set_var(self, varname, value):
self.action_cnt += 1
self.extras['action' + str(self.action_cnt)] = {'action': self.SET_VARIABLE, 'arg:1': varname, 'arg:2': value, 'arg:3': False, 'arg:4': False, 'arg:5': False}
def run_task(self):
taskIntent = droid.makeIntent('net.dinglisch.android.tasker.ACTION_TASK', None, None, self.extras).result
droid.sendBroadcastIntent(taskIntent)
def set_var_now(self, varname, value):
self.new_task()
self.set_var(varname, value)
self.run_task()
temps = 20
droid.startSensingTimed(1,500)
while temps > 0:
time.sleep(0.5)
x, y, z = droid.sensorsReadOrientation().result
temps = temps - 1
if x is not None:
break
droid.stopSensing()
t = Task()
t.new_task()
if x is not None:
t.set_var("%ORIENTATION_X", str(x))
t.set_var("%ORIENTATION_Y", str(y))
t.set_var("%ORIENTATION_Z", str(z))
t.set_var("%ORIENTATION", "Done")
t.run_task()
droid.wakeLockRelease()
But i still have problem. No effect to use wakeLock

Related

PDA goes to sleep/ Process ID

Hi,
I am having problems with keeping my application alive as the pda keeps going into 'sleep' mode. I realise that i can't just keep the pda switched on as the battery will just die, so i have a little program which does a RunAppAtTime call, and then checks to see if my application is alive. I expected that i would either have an error or would get a process id of -1 etc if the process wasn't alive. I am using VB.net and OpennetCF to do the code here is a code snippet. Hope someone can help, i need to finish this before friday.
Dim intProcessID As Integer
Dim Process As New OpenNETCF.Diagnostics.Process
Dim NewProcess As OpenNETCF.Diagnostics.Process
Dim info As New OpenNETCF.Diagnostics.ProcessStartInfo
Dim OldProcess As New OpenNETCF.Diagnostics.Process
Try
intProcessID = ReadID()
ldProcess = OpenNETCF.Diagnostics.Process.GetProcessById(intProcessID)
If (OldProcess.Id = -1) Or (OldProcess.Id <> intProcessID) Then
info.FileName = "\Storage\AutoSync.exe"
info.UseShellExecute = False
NewProcess = Process.Start(info)
intProcessID = NewProcess.Id
WriteProcID(intProcessID)
Else
WriteFile("Processexists" & DateTime.Now)
End If

CSD GSM communication...

Hi!
Could someone give me point about CSD GSM communication?
What is done:
I have connected 2 Qtek S100 through data-call:
- use TAPI - get “connected”
- take handle to COMM
- init COMM: 9600/ e.t.
- successfully transfer data
But several strange things I have:
1. average transfer rate – channel capacity - for transparent mode (S100 allows to manipulate transparent/non-transparent mode) is 6.4k bit/sec. – and this is write to COMM. speed! i.e. transferring side shows this speed by simple WriteFile() operation for chunk of data for example 64k bytes. Some times I receive corrupted data – but it’s ok for me. – transfer rate is strange!
2. average transfer rate for non-transparent mode is 8.8k bit/sec.- some times I see dropped series of bytes and equation: received + dropped == transferred is correct – so all is ok and speed is ok too ~1100 data bytes per sec +1 for stop-bits and +start-bit(? – not sure).
3. _most_ interesting for me – after some number of errors the connection is dropped – I achieve Line IDLE state.
So – most interesting for me is 3. – I don’t wanna lost connection – I am agree to have some errors in communication – but I don’t want to make call again.
As I understand construction (coarsely) is
COMM->RIL
So does it mean I have to go inside RIL to set something to preserve “connection state”?
And same for transparent mode – does it something inside RIL to set for “improving” channel capacity from 6.4k close to expected 9.6k bits/sec?
Here is my DCB settings
Code:
PortDCB.BaudRate = CBR_9600; // Current baud
PortDCB.ByteSize = 8; // Number of bits/byte, 4-8
PortDCB.Parity = NOPARITY; // Parity odd,even,mark,space
PortDCB.fBinary = TRUE; // Binary mode; no EOF check
PortDCB.fParity = FALSE; // No parity checking
PortDCB.fOutxCtsFlow = FALSE; // CTS output flow control
PortDCB.fOutxDsrFlow = FALSE; // No DSR output flow control
PortDCB.fDtrControl = DTR_CONTROL_ENABLE; //DTR output ON
PortDCB.fRtsControl = RTS_CONTROL_ENABLE; //RTS_CONTROL_HANDSHAKE;
PortDCB.fDsrSensitivity = FALSE; // DSR sensitivity
PortDCB.fTXContinueOnXoff = TRUE; // XOFF continues Tx
PortDCB.fOutX = FALSE; // No XON/XOFF out flow control
PortDCB.fInX = FALSE; // No XON/XOFF in flow control
PortDCB.fErrorChar = FALSE; // Disable error replacement
PortDCB.fNull = FALSE; // Disable null stripping
PortDCB.fAbortOnError = FALSE; // Do not abort reads/writes on error
PortDCB.StopBits = ONESTOPBIT; // 0,1,2 = 1, 1.5, 2
how to stay connected?
Thanks for any advice.
a guess.....
Try transferring less data per write. Also you probably do not need to alter any of the port settings. They normally work fine the way they are. You would still need to set com time outs for the read/write opperation.
As an experiment just omit all your port settings and try transfering 1 byte at a time. If it still drops out it could be your quality of service.
yes - use smaller portion may help me.
but I think it just masks effect of line drop - interest is: what a reason to line-drop and what parameters influences on it?
some level of error per some period of time - or what?
thanks anyway.

volume setting

I am trying to set the volume to my needs then put it back after. I have use the code from ppc developer network and when that did not set the correct volume I also did the registry as well. Don't worry about "reg", its my registry class and it works fine.
DWORD oldReg=0;
oldReg=reg->readDWORDfromReg(name,path);
reg->saveDWORDtoRegistry(name,path,0xffffffff);
WAVEFORMATEX wf;
wf.wFormatTag = WAVE_FORMAT_PCM;
wf.nChannels = 1;
wf.nSamplesPerSec = 8000 * 1000;
wf.wBitsPerSample = 8;
wf.nBlockAlign = wf.nChannels * wf.wBitsPerSample / 8;
wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
wf.cbSize = 0;
HWAVEOUT hwo;
DWORD dwVolume=0xffffffff;
DWORD oldVolume=0;
int waveDevice=-1;
UINT numberOfDevices=waveOutGetNumDevs();
for(UINT id=0;id<numberOfDevices;id++)
{
if (waveOutOpen(&hwo,id,&wf,0,0,CALLBACK_NULL)==MMSYSERR_NOERROR)
{
waveDevice=id;
waveOutGetVolume(hwo,&oldVolume);
waveOutSetVolume(hwo,dwVolume);
waveOutClose(hwo);
break;
}
}
.........playing sound here all ok....
//put the volume back
if(waveDevice!=-1)
{
if (waveOutOpen(&hwo, waveDevice, &wf, 0, 0, CALLBACK_NULL) == MMSYSERR_NOERROR)
{
waveOutSetVolume(hwo, oldVolume);
waveOutClose(hwo);
}
}
reg->saveDWORDtoRegistry(name,path,oldReg);
I can set the volume to any value below the origional volume but any attempt to set a volume higher just dose nothing. There are no errors (checking left out here), just the same level. I did not seriously expect the registry part to work as I guess there is some event to trigger that change, but others seem to get results from waveOutSetVolume.
Well, I never tried changing volume by code, but I know TCPMP player does it well and it's open source so might be worth taking a look at.
Thanks levenum, I will give it a look.
Before I got a chance to look at that code I got a result. I have been using PlaySound to play a resource with no volume change working. When I use waveOutWrite to play a buffer containing the same data I can get the volume change I am after. There is still something wrong with my code because the sound gets garbled but I think I will figure that part out. I also want to next test playsound with a file instead of a resource.
<edit>
using playsound with the same file plays clear sound but the volume change is not working. Its a pity because to get the waveoutwrite to work properly i had to fill in the WAVEFORMATEX with the CORRECT values. This means that if I am allowing the user to specify files to play I will have to find out the samples per second and bits per sample info before I can use the file.

Help with CeRunAppAtEvent

Hey all,
I'm trying to register an application to run during a Windows Mobile event using CeRunAppAtEvent (from CoreDll.dll). I'm having difficulty getting this to happen.
Here is the syntax for the native method:
Code:
BOOL CeRunAppAtEvent(
TCHAR* pwszAppName,
LONG lWhichEvent
);
Here is the code in my application (C#):
Code:
[DllImport("coredll.dll", EntryPoint = "CeRunAppAtEvent", SetLastError = true)]
private static extern bool CeRunAppAtEvent(string pwszAppName, int lWhichEvent);
private void menuItem1_Click(object sender, EventArgs e)
{
if (CeRunAppAtEvent(@"\Windows\Calc.exe", 3))
{
MessageBox.Show("Event registered!");
}
else
{
MessageBox.Show("Event did not register.");
}
}
Note that I'm using the argument '3' for lWhichEvent, which is based upon this understanding of how lWhichEvent argument works:
Code:
> NOTIFICATION_EVENT_NONE = 0,
> NOTIFICATION_EVENT_TIME_CHANGE = 1,
> NOTIFICATION_EVENT_SYNC_END = 2,
> NOTIFICATION_EVENT_ON_AC_POWER = 3,
> NOTIFICATION_EVENT_OFF_AC_POWER = 4,
> NOTIFICATION_EVENT_NET_CONNECT = 5,
> NOTIFICATION_EVENT_NET_DISCONNECT = 6,
> NOTIFICATION_EVENT_DEVICE_CHANGE = 7,
> NOTIFICATION_EVENT_IR_DISCOVERED = 8,
> NOTIFICATION_EVENT_RS232_DETECTED = 9,
> NOTIFICATION_EVENT_RESTORE_END = 10,
> NOTIFICATION_EVENT_WAKEUP = 11,
> NOTIFICATION_EVENT_TZ_CHANGE = 12,
> NOTIFICATION_EVENT_MACHINE_NAME_CHANGE = 13
I've tried registering Calc and a few other applications unsuccessfully--the program tells me the event registers (so the method call is returning true), yet the applications do not launch upon the event change (plugging into AC power, for example). Any ideas to what I'm doing wrong?
Bump. Any ideas?
Hello shidell
I also found, that not all possible wakeups are possible on every device. I assume it is OEM related and the implementation of these events is not mandatory for WM platform builds.
See also hjgode.de/dev and look for iRunAtEvent and iRunOnEnet. The latter is a workaround for enet detection.
I recently did try to use ON_AC_POWER and it did not work. The event registration was OK but the event was not signaled on AC power connection. I worked around it and changed my code to run on wakeup, which works OK on this particular device (CK61 running WinCE5).
As a workaround, you could go the way I did in iRunOnEnet. Instead of watching the enet connection you have to check the PowerStatus structure for ON AC POWER.
regards
josef
You are right, not every event can be handled with CeRunAppAtEvent and here are the events that have to works on every device:
Code:
Const NONE = 0
Const TIME_CHANGE = 1
Const SYNC_END = 2
Const DEVICE_CHANGE = 7
Const RS232_DETECTED = 9
Const RESTORE_END = 10
Const WAKEUP = 11
Const TIME_ZONE_CHANGE = 12
Good approach will be to check your application's path by using:
Code:
System.IO.File.Exists(<application>)
because for example in my ROM that "calc.exe" is actually "calculator.exe"... and of course CeRunAppAtEvent will return True, because the event handler will be registered no matter file exists or not
Hope this helps.
Best regards,
aDEO

InTheHand Bluetooth - Weird stream problems

I am currently working on my "SciLor's WiMoBlue". The new protocol is ready. Everything works fine, until I send much data at the same time.
For example if I try to send an image in that way:
Code:
Public Sub SendImage(ByVal Image As Bitmap, ByVal Position As Point, ByVal Format As ImageFormat)
Dim PosX, PosY, Width, Height As Byte()
Dim ImageStream As New IO.MemoryStream
Dim ImageLength As Integer
Dim ImageLengthBytes As Byte()
Dim ImageBuffer(MaxChunkSize - HeaderSize - 1) As Byte
PosX = BitConverter.GetBytes(Position.X)
PosY = BitConverter.GetBytes(Position.Y)
Width = BitConverter.GetBytes(Image.Width)
Height = BitConverter.GetBytes(Image.Height)
Image.Save(ImageStream, ImageFormat2ImagingFormat(Format))
ImageStream.Seek(0, SeekOrigin.Begin)
ImageLength = ImageStream.Length
ImageLengthBytes = BitConverter.GetBytes(ImageLength)
SendData(BuildCommand(BaseProtocol.Image, ImageProtocol.Initiate, CombineBytes(PosX, PosY, Width, Height, ImageLengthBytes)))
Thread.Sleep(2000)
Dim DataPos As Integer
For DataPos = 0 To ImageStream.Length - MaxChunkSize - HeaderSize - 1 Step MaxChunkSize - HeaderSize
ImageStream.Read(ImageBuffer, 0, MaxChunkSize - HeaderSize)
SendData(BuildCommand(BaseProtocol.Image, ImageProtocol.Data, ImageBuffer))
'WaitForNextChunk = True
'Do While WaitForNextChunk = True
'Loop
'Thread.Sleep(2000)
Next
ImageBuffer = New Byte(ImageLength - DataPos - 1) {}
ImageStream.Read(ImageBuffer, 0, ImageBuffer.Length)
SendData(BuildCommand(BaseProtocol.Image, ImageProtocol.End, ImageBuffer))
End Sub
SendData:
Code:
If Data.Length > MaxChunkSize Then
MsgBox("Data to long... " & vbNewLine & "SendSize:" & Data.Length & vbNewLine & "MaxSize:" & MaxChunkSize)
Else
If btClient.Connected = True And isRecieving = True Then
btStream.Write(Data, 0, Data.Length)
btStream.Flush()
End If
End If
Recieving Part:
Code:
While isRecieving = True
If btStream IsNot Nothing And btStream.DataAvailable = True Then
Try
Recieved = btStream.Read(myHeader, 0, myHeader.Length)
If myHeader(0) = HeaderIdentifier And myHeader(1) = OtherModeHeader Then
btStream.Read(myDataSize, 0, 2)
DataLength = BitConverter.ToInt16(myDataSize, 0)
myBuffer = New Byte(DataLength - 1) {}
Recieved = 0
Do Until Recieved = DataLength
If btStream.DataAvailable = True Then
Recieved += btStream.Read(myBuffer, Recieved, DataLength - Recieved)
End If
Loop
ExecuteCommand(myHeader(2), myHeader(3), myBuffer)
Else
Debug.WriteLine("WrongData")
Exit While
End If
Catch ex As Exception
Debug.WriteLine(ex.Message)
If Recieved = 0 Then
Exit While
End If
End Try
End If
End While
If I send the image, without Thread.Sleeps (huighe ones). The recieving stream gets weird. The gets btStream.DataAvailable = False forever. If I remove that ckeck, it hangs at the btStream.Read.
I also tried to fix that with waiting for the answer of the server, but the problem doesn't get solved.
Do you have any idea how to fix that problem?. In that speed the image sending is worthless
SciLor

Categories

Resources