Sl4a - eventRegisterForBroadcast - CALL_STATE_RINGING - sl4a

I register a listerner for a CALL_STATE_RINGING broadcast signal. i open up a socket to read for events postet. when you run this command in this line (f.readline()), the Console depends on. i don't know, what i do wrong?
import android
import socket
from json import loads
def parseEvent(line):
out = loads(line)
out.update(loads(out["data"]))
return out
####connected via USB
droid = android.Android()
ACTION="android.telephony.TelephonyManager.CALL_STATE_RINGING"
droid.eventRegisterForBroadcast(ACTION, False)
####at this line, i can see my Action registred
print droid.eventGetBrodcastCategories()
p=droid.startEventDispatcher().result
####at this line, i see the Port
print p
s=socket.socket()
s.connect(('localhost', p))
f=s.makefile()
##Problem
###when you run this command in this line, the Console depends on
print f.readline()
while True:
print 'test'
event = parseEvent(f.readline())
print event
droid.log(str(event))
print "got", event
print droid.eventUnregisterForBroadcast(ACTION)
print droid.eventGetBrodcastCategories()

Related

Trying to find a way where a discord bot can randomly send a message in a given channel

I'm using the commando framework. I want the bot I'm making to be able start randomly sending messages in a certain channel when given a command to do so. For example if I typed "!radar" I would expect the bot to continue to randomly send a predetermined message in that channel until it is told to stop.
Here's the code I attempted to use:
async run(message){
message.say("Scanning....")
while(true){
var number = 30;
var imageNumber = Math.floor (Math.random() * (number - 1 + 1)) + 1;
if(imageNumber == 1){
message.say("^ detected!");
}
}
}
When I attempt this code I don't seem to get any errors logs, but I don't get any response from the bot when I send the command.

Send and receive a w3c.dom.Document over socket as byte[] Java

I send a document over socket like this:
sendFXML(asByteArray(getRequiredScene(fetchSceneRequest())));
private void sendFXML(byte[] requiredFXML) throws IOException, TransformerException {
dataOutputStream.write(requiredFXML);
dataOutputStream.flush();
}
private Document getRequiredScene(String requiredFile) throws IOException, ParserConfigurationException, SAXException, TransformerException {
return new XMLLocator().getDocumentOrReturnNull(requiredFile);
}
private String fetchSceneRequest() throws IOException, ClassNotFoundException {
return dataInputStream.readUTF();
}
On the side of XMLLocator it finds the correct document and parses it right. I see it by printing the whole doc in console.
But I cannot handle it on the clients side where it's fetch by:
public static void receivePage() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] data = new byte[989898];
int bytesRead = -1;
while((bytesRead = dataInputStream.read(data)) != -1 ) { //stops here
baos.write(data, 0, bytesRead );
}
Files.write(Paths.get(FILE_TO_RECEIVED), data);
}
After the first iteration in while() cycle it just stops on the commented place.
I don't know if I have an error on the side of the server and I send this in doc in an incorrect format or I read the sent byte array incorrectly. Where is the problem?
Edit:
For the debug purpose, in the receivePage() method, I've chosen a different way of reading the byte array from server which goes like:
int count = inputStream.available();
byte[] b = new byte[count];
int bytes = dataInputStream.read(b);
System.out.println(bytes);
for (byte by : b) {
System.out.print((char)by);
}
And now I'm able to print fetched FXLM in console but a new problem has appeared.
On debug, it normally receives the byte[] from server, writes 2024 for count and displayes the content of the file but if I run the app normally via Shift + f10 it fetches nothing and just writes 0 in console
Edit2:
For some reason, once again, on debug, it's able to even write into a file
for (byte by : b) {
Files.write(Paths.get(FILE_TO_RECEIVED), b);
System.out.print((char)by);
}
But when I try to return this fxml on debug and then show like this:
Parent fxmlToShow = FXMLLoader.load(getClass().getResource("/network/gui.fxml"));
Scene childScene = new Scene(fxmlToShow);
Stage window = (Stage)((Node)ae.getSource()).getScene().getWindow();
window.setScene(childScene);
return window;
It shows only previous files. Like on the first attempt of debug it show a blank page when I asked for the 1st one from server. On the second attempt of debug when i ask for 3rd page from server, it shows me the previously asked one and so on.
To me, it seems absolutely insane cuz the fxml rile actually refreshes before the line
Parent fxmlToShow = FXMLLoader.load(getClass().getResource("/network/gui.fxml"));
is invoked.
Yeah, thank everybody for participating.
So, the issue of incorrect displaying if FXML files was caused by the incorrect FILE_TO_RECEIVED path.
When FXMLLoader.load(getClass().getResource("/network/gui.fxml")); loads gui.fxml it takes it not from D:\\JetBrains\\IdeaProjects\\Client\\src\\network\\gui.fxml,im my case, but from D:\\JetBrains\\IdeaProjects\\Client\\OUT\\PRODUCTION\\Client\\network\\gui.fxml.
As for me, that doesn't seem obvious.
What about different behaviour on debug and on run. In method receivePage() it needs to wait until connection is available.
int count = inputStream.available();
If you read docs for this method you will see
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream ...
The available method for class InputStream always returns 0...
So, you jext need to wait for connection to be available
while(inputStream.available()==0){
Thread.sleep(100);
}
Otherwise it just prepares byte[] b = new byte[count]; for 0 bytes and you can write in nothing.

[]byte{10} or []byte("\n") vs []byte{92, 110}

I'm working with github.com/tarm/serial to interface with some serial instrumentation. In development, I'm working with the /dev/ttyp0 and /dev/ptyp0 pair, where my go process connects to one and I use screen to connect to the other. I've written a function that, combined with serial.Config.ReadTimeout, reads for up to ReadTimeout or a given byte sequence is received. That function is:
func readToTermination(s serial.Port, termination []byte, rate time.Duration) []byte {
var out []byte
lterm := len(termination)
for {
buf := make([]byte, 128)
n, _ := s.Read(buf)
out = append(out, buf[:n]...)
l := len(out)
if l >= lterm {
if bytes.Compare(out[l-lterm:], termination) == 0 {
break
}
}
time.Sleep(rate)
}
return out
}
This avoids burning up CPU cycles doing nothing with a debounce. When I test with termination = []byte("\n") and screen, the break never triggers because it turns into []byte{97, 11} (two distinct elements, something like screen flushing after each keystroke). On the other hand, if I do something like echo "foo" > /dev/ptyp0, the break triggers correctly. Echo implicitly seems to be sending a \n, or the closing of the connection does so. I see \r\n for echo foo and \r\n\r\n for echo "foo\n".
So my question is:
(1) why is there a difference in behavior here?
(2) how do I get the behavior I really am after with a carriage return for the termination? Perhaps I should use EOT instead? A human will never be typing into this directly.

I want to send \x0a as byte, not as \n

I would like to send a byte string to my device that gets the data from serial port (RS422).
I have to send my byte string as "\x0a\x23\x01..." but Python (2.7) gets \x0a as a new line character (ASCII), therefore I can't send the rest of the bytes.
How can I send "\x0a" as a byte, not as a new line? Below, you can find my code (In the code below, I just write my bytestring to a port, then read&print it on the same device from another port).
import serial
import binascii
class test_Tk():
def __init__(self):
self.serialPortWrite = serial.Serial('COM6', 921600, timeout=0.5)
self.serialPortRead = serial.Serial('COM7', 921600, timeout=0.5)
self.byte1 = "\x0a"
self.byte2 = "\x23"
self.byte3 = "\x01"
self.bytestring = "\xaa\xab\xac\xad"
self.data = self.byte1 + self.byte2 + self.byte3 + self.bytestring
self.serialPortWrite.write(self.data)
self.read = self.serialPortRead.readline(100)
print binascii.hexlify(self.read)
test_Tk()
I get output "0a", however I should have gotten "0a2301aaabacad".
Thanks!

Groovy script to modify text file line by line

I have a input file from which a Groovy file reads input. Once a particular input is processed, Groovy script should be able to comment the input line it used and then move on.
File content:
1
2
3
When it processes line 1 and line 2, the input file will look as below:
'1
'2
3
By this way, if I re-run the Groovy, I would like to start from the line it stopped last time. If a input was used and it failed, that particular line shall not be commented (') so that a retry can be attempted.
Appreciate if you can help to draft a Groovy script.
Thanks
AFAIK in Groovy you can only append text at the end of the file.
Hence to add ' on each line when it is processed you need to rewrite the entire file.
You can use the follow approach but I only recommend you to use for a small files since you're loading all the lines in memory. In summary an approach for your question could be:
// open the file
def file = new File('/path/to/sample.txt')
// get all lines
def lines = file.readLines()
try{
// for each line
lines.eachWithIndex { line,index ->
// if line not starts with your comment "'"
if(!line.startsWith("'")){
// call your process and make your logic...
// but if it fails you've to throw an exception since
// you can not use 'break' within a closure
if(!yourProcess(line)) throw new Exception()
// line is processed so add the "'"
// to the current line
lines.set(index,"'${line}")
}
}
}catch(Exception e){
// you've to catch the exception in order
// to save the progress in the file
}
// join the lines and rewrite the file
file.text = lines.join(System.properties.'line.separator')
// define your process...
def yourProcess(line){
// I make a simple condition only to test...
return line.size() != 3
}
An optimal approach to avoid load all lines in memory for a large files is to use a reader to read the file contents, and a temporary file with a writer to write the result, and optimized version could be:
// open the file
def file = new File('/path/to/sample.txt')
// create the "processed" file
def resultFile = new File('/path/to/sampleProcessed.txt')
try{
// use a writer to write a result
resultFile.withWriter { writer ->
// read the file using a reader
file.withReader{ reader ->
while (line = reader.readLine()) {
// if line not starts with your comment "'"
if(!line.startsWith("'")){
// call your process and make your logic...
// but if it fails you've to throw an exception since
// you can not use 'break' within a closure
if(!yourProcess(line)) throw new Exception()
// line is processed so add the "'"
// to the current line, and writeit in the result file
writer << "'${line}" << System.properties.'line.separator'
}
}
}
}
}catch(Exception e){
// you've to catch the exception in order
// to save the progress in the file
}
// define your process...
def yourProcess(line){
// I make a simple condition only to test...
return line.size() != 3
}

Resources