I have 1 JDY-08 MASTER that scans looking for myDeviceName and triggers a function when it finds that device name.
String get_ble_scan_data(void){
String final_result = "";
String result = "";//reset and declare
String extract = set_ble("AT+SCAN1");//scan for device name, signal strength and mac address
String extract2 = set_ble("AT+GETDCD");//get number of device found
//now we are going to check for which extraction has the data we interested in
if((extract.length() > threshold or extract.length() > threshold)){
result = extract;//pass extract as result
if(extract2.length() > extract.length()){//check which is bigger
result = extract2;//pass extract2 as result if its bigger in length than extract
}
}
if(result.length() > 0){//add filter and execution here
String filter = result;//copy
result = "";// reset
while(filter.indexOf('=') > -1){// we use the char = as a seperator
filter = filter.substring(filter.indexOf('=') + 1);//remove strings before seperator
result += filter.substring(0, filter.indexOf('\n')) + ' '; //extract till newline character
filter = filter.substring(filter.indexOf(result) + result.length());//remove extracted result so we go on to next extraction of same result if there is more device picked up
detect
}
result.trim();//remove spaces at the end or start if any
final_result = result;
}
return final_result;
}
void ble_response(String search_result){
String scan_result = search_result;//do bluetooth scan
if(scan_result.indexOf(myDeviceName) > -1 ){//when data present in scan and it contains desired key
if(scan_result.indexOf(' ') == -1){//if only one ble is picked up
ble_macaddress = scan_result.substring(0, scan_result.indexOf(','));
scan_result = scan_result.substring(scan_result.indexOf(ble_macaddress) + 1 + ble_macaddress.length(), scan_result.length());//remove mac address
ble_strength = scan_result.substring(0, scan_result.indexOf(','));
ble_name = scan_result.substring(scan_result.indexOf(ble_strength) + 1 + ble_strength.length(), scan_result.length());//remove mac address
if(((int) ble_strength.toFloat()) >= trigger_threshold and ble_name == key){
trigger_action();
}
}else{//if multiple ble is picked up
String cut = "";
while(scan_result.indexOf(',') > -1){//while there is still result to be processed
cut = scan_result.substring(0, scan_result.indexOf(' '));
scan_result = scan_result.substring(scan_result.indexOf(cut) + 1 + cut.length(), scan_result.length());
if(cut.indexOf(myDeviceName) > -1){//only analyze if it contains key
ble_macaddress = cut.substring(0, cut.indexOf(','));
cut = cut.substring(cut.indexOf(ble_macaddress) + 1 + ble_macaddress.length(), cut.length());//remove mac address
ble_strength = cut.substring(0, cut.indexOf(','));
ble_name = cut.substring(cut.indexOf(ble_strength) + 1 + ble_strength.length(), cut.length());//remove mac address
if(((int) ble_strength.toFloat()) >= trigger_threshold and ble_name == key){
trigger_action();
break;
}
}
}
}
}
If I use another JDY-08 device with one button, It finds the device and triggers the action:
if(!digitalRead(11)){//if button is pushed///////
delay(500);
set_ble("AT+NAMEmyDeviceName");//change ble name
while(!digitalRead(11));//do nothing while button is still pressed
delay(2000);//allow time before name change back
set_ble("AT+NAMEJDY-08");//change name back
But when I use the phone It doesn´t trigger the action:
private void advertise(){
final BluetoothLeAdvertiser advertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
final AdvertiseSettings settings = new AdvertiseSettings.Builder()
.setAdvertiseMode( AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY )
.setTxPowerLevel( AdvertiseSettings.ADVERTISE_TX_POWER_HIGH )
.setConnectable( true )
.build();
final AdvertiseData data = new AdvertiseData.Builder()
.setIncludeDeviceName( true )
.build();
final AdvertiseCallback advertisingCallback = new AdvertiseCallback() {
#Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
}
#Override
public void onStartFailure(int errorCode) {
Log.e( "BLE", "Advertising onStartFailure: " + errorCode );
super.onStartFailure(errorCode);
}
};
advertiser.startAdvertising(settings,data,advertisingCallback);
final Handler myTimerHandler = new Handler();
myTimerHandler.postDelayed(
new Runnable()
{
#Override
public void run(){
advertiser.stopAdvertising(advertisingCallback);
}
} , 30000);
}
I also use the intent with BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE.
Using NRFConnect app, I can see how the JDY-08 Button device changes the device name (That triggers the action on the JDY-08 MASTER). I can also see the Android device with myDeviceName but this does not trigger the action. Am I missing something in the Android app?
The problem was that the JDY-Master only received the name of JDY devices. All other devices show mac address and signal strength only.
Related
This is how my code is looking :
public void onGuildVoiceJoin(GuildVoiceJoinEvent event) {
String channelId = event.getChannelJoined().getId();
if (channelId.equals("904375329764814870")) {
Member member = event.getMember();
String memberName = event.getMember().getEffectiveName();
Category category = event.getGuild().getCategoryById("904364634507706468");
event.getGuild().createVoiceChannel("Coaching " + memberName).setParent(category).complete();
List<VoiceChannel> channelList = event.getGuild().getVoiceChannelsByName("Coaching " + memberName, true);
VoiceChannel channel = channelList.get(0);
event.getGuild().moveVoiceMember(member, channel).queue();
while (true){
event.getGuild().getTextChannelById("904364671467929610").sendMessage(
"Number of people currently on the channel : " + channel.getMembers().size()
).queue();
wait(3000);
}
My goal is to get the number of people currently inside the channel.
I thought the getMembers() method was the good method, but it's not working
I use the infinite while to see if the channel.getMembers().size() changes when i join/leave the channel but it still return 0.
How can i fix this ? And get the correct amount of people inside the channel as return.
The final goal of my code is to delete the channel when he's empty of user
This can be achieved by just checking the member count in the GuildVoiceUpdateEvent:
public void onGuildVoiceUpdate(GuildVoiceUpdateEvent event) {
if (channel.getName().startsWith("Coaching ")) { // check if name matches the desired name
if (channel.getMembers().isEmpty()) { // check if channel is empty
channel.delete().queue(); // delete channel
}
}
}
ArrayList prayerTimes = prayers.getPrayerTimes(cal, latitude,longitude,timezone);
ArrayList prayerNames = prayers.getTimeNames();
for (int i = 0; i < prayerTimes.size(); i++) {
txtPrayerTimes.append("\n" + prayerNames.get(i) + " - "+ prayerTimes.get(i));
Screenshot of output to this point
Now I want to activate silent mode if current time = fajr time i.e 03:48 AM
My code so far, which I'm sure is crap...
if(getReminingTime()== prayerTimes.get(0)) {
Toast.makeText(getApplicationContext(), "Peace mode activated",Toast.LENGTH_SHORT).show();
AudioManager audioManager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}}}
private String getReminingTime(){
String delegate = "hh:mm aaa";
return (String) DateFormat.format(delegate,Calendar.getInstance().getTime());}
What is the correct way to enable silent mode on the device?
I am trying to read IRC and pull data from individual IRC messages in Processing. You can see the code (also with twitter library, ignore that) and I need some pointers on how I can pull the data out in the format of Nick:Message so it can be displayed in a visualization.
//Twitter
import twitter4j.conf.*;
import twitter4j.*;
import twitter4j.auth.*;
import twitter4j.api.*;
import java.util.*;
// Import the net libraries
import processing.net.*;
// Declare a client
Client client;
Twitter twitter;
String searchString = "god";
List<Status> tweets;
String server = "irc.twitch.tv";
String nick = "NugShow";
//String user = "simple_bot";
int port = 6667;
String channel = "#nugshow";
String password = "xx";
String in = "butt";
String checkFor;
//bools
Boolean isLive = false;
int privMsgIndex;
int atIndex;
String playerSubstring;
// The channel which the bot will joString channel = "#irchacks";
int currentTweet;
void setup()
{
size(800,600);
frameRate(60);
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("xx");
cb.setOAuthConsumerSecret("xx");
cb.setOAuthAccessToken("xx");
cb.setOAuthAccessTokenSecret("xx");
TwitterFactory tf = new TwitterFactory(cb.build());
twitter = tf.getInstance();
getNewTweets();
currentTweet = 0;
thread("refreshTweets");
thread("loopChat");
connectToServer();
//IRC
}
void draw()
{
if (client.available() > 0) {
String in = client.readString();
println(in);
}
if (isLive == false){
if (client.available() > 0) {
}
} else {
}
/*
fill(0, 40);
rect(0, 0, width, height);
currentTweet = currentTweet + 1;
if (currentTweet >= tweets.size())
{
currentTweet = 0;
}
Status status = tweets.get(currentTweet);
fill(200);
text(status.getText(), random(width), random(height), 300, 200);
delay(100);
*/
}
void joinChannel() {
String in = client.readString();
client.write( "JOIN " + channel + "\n\r" );
client.clear();
in = client.readString();
println(in);
if (in != null){
//println("Recieved data");
println(in);
//String inString = myClient.readStringUntil("");
isLive = true;
println(isLive);
}
}
void connectToServer()
{
client = new Client(this, server , 6667);
client.write( "PASS " + password + "\n\r" );
println(password + " sent!");
client.write( "NICK " + nick + "\n\r" );
println(nick + " sent!");
joinChannel();
}
void getNewTweets()
{
try
{
Query query = new Query(searchString);
QueryResult result = twitter.search(query);
tweets = result.getTweets();
}
catch (TwitterException te)
{
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
}
void refreshTweets()
{
while (true)
{
getNewTweets();
println("Updated Tweets");
delay(30000);
}
}
void loopChat()
{
while (true)
{
if (privMsgIndex != 0){
println(privMsgIndex);
//privMsgIndex = privMsgIndex - 15;
atIndex = in.indexOf("#");
println(atIndex);
//atIndex = atIndex + 1;
playerSubstring = in.substring(atIndex, privMsgIndex);
println(playerSubstring);
} else {
println("looped");
}
delay(300);
client.clear();
in = null;
}
}
void keyPressed()
{
}
void tweet()
{
try
{
Status status = twitter.updateStatus("This is a tweet sent from Processing!");
System.out.println("Status updated to [" + status.getText() + "].");
}
catch (TwitterException te)
{
System.out.println("Error: "+ te.getMessage());
}
}
The chat commands look like this: :nugshow!nugshow#nugshow.testserver.local PRIVMSG #nugshow :dddd where nugshow is the username, #nugshow is the channel, and dddd is the message. I need to get it into the format of nugshow: dddd.
there is a lot of header information that I'm not sure how to strip out of client.recieved buffer as well, it looks like this:
:testserver.local 001 nugshow :Welcome, GLHF!
:testserver.local 002 nugshow :Your host is testserver.local
:testserver.local 003 nugshow :This server is rather new
:testserver.local 004 nugshow :-
:testserver.local 375 nugshow :-
:testserver.local 372 nugshow :You are in a maze of twisty passages, all alike.
:testserver.local 376 nugshow :>
:nugshow!nugshow#nugshow.testserver.local JOIN #nugshow
:nugshow.testserver.local 353 nugshow = #nugshow :nugshow
:nugshow.testserver.local 366 nugshow #nugshow :End of /NAMES list
:jtv!jtv#jtv.testserver.local PRIVMSG nugshow :HISTORYEND nugshow
I would not recommend regex here. At least not if you want to be able to catch all types of IRC messages. The key is to look at the message code to know what you can actually get out of the message. As I'm also writing an IRC-client (just for giggles) I have some notes for you.
Be sure to answer any PINGs that the server sends you so you don't get kicked off. As the PING is sent with an identifier, you need to catch that and send it back. A simple way to do this is to check the last line that was sent from the server and substring it.
String line = inputStream.readLine();
if(line.substring(0,4).equals("PING")){
send("PONG " + line.substring(5)); // Assume you have some send-function.
}
This will make sure you don't get kicked off and can proceed to actually stay on a server.
As I mentioned, I do not recommend using regex for this as it would become a RegEx-of-doom. So, what I have done is to just split the line you get and put all the results in a String array.
String[] arr = line.split(" ");
As you know by your own message line you have posted, the IRC protocol separates things with spaces. So splitting at spaces in not all that shabby (we'll get how to deal with actual text in a bit).
The basic structure that is always the same (as far as I can tell) in messages is PREFIX COMMAND PARAM PARAM/TRAILING. So what does this mean? The PREFIX is where the message was sent from. Example ":user!user#host.com". The COMMAND is what the line actually is. You are looking for PRIVMSG here, but there are many, many, others that you might want to take care of. Like JOIN, PART, QUIT, 332 (current topic), 353 (nicks in channel, 404 (unable to send to channel), etc. etc. The PARAM and PARAM/TRAILING will all depend on the COMMAND.
So, what do we gain from splitting at spaces? This:
arr[0] = :user!user#host.com
arr[1] = COMMAND
arr[2] = PARAM
arr[3 onwards] = rest
We can now easily manage every command in it's own needed way.
Without further delay, lets get to your actual question, the PRIVMSG.
I will use this string: ":Chewtoy!chewtoy#stackoverflow.com PRIVMSG #stackoverflow :Ty: I saw your question and thought I should give you an answer."
After doing a split at the spaces, we get the array
arr[0] = :Chewtoy!chewtoy#stackoverflow.com
arr[1] = PRIVMSG
arr[2] = #stackoverflow
arr[3] = :Ty:
arr[4] = I
arr[5] = saw
...
As you can see, everything from 3 and onwards is the message you want. 0-2 is stuff that you need to be able to know who sent what where. My code for getting all this looks like this:
String[] arr = receivedLine.split(" ");
if(arr[1].equals("PRIVMSG")){
String[] usr = arr[0].split(!"); // Get the user, which is in usr[0]. Host in usr[1]
StringBuilder msg = new StringBuilder();
for(int i=3; i<arr.length; i++){ // We know the message starts at arr[3], so start counting from that.
msg.append(arr[i] + " ");
}
String chan = "";
if(arr[2].substring(0,1).equals("#")){ // We need to differentiate between sending to channel and sending a PM. The only difference in this is where the text is sent.
chan = arr[2];
} else{
chan = usr[0].substring(1); // substring(1) because we want Chewtoy, not :Chewtoy
}
// The result here will be:
// <#stackoverflow> Chewtoy: Ty: I saw your question and thought I should give you an answer.
sendItAllToWhereYouWantIt("<" + chan +"> " + usr[0].substring(1) + ": " + msg.substring(1));
}
Hope that helps.
My app works just fine with any Android version before 4.3. I mean when I input a word into edWord (EditText field), a list of similarly-spelled words will appear in the list view.
But in Android 4.3, it always returns null, claiming that app_ContentProvider cannot find the supported uri.
I use the following code to show the word list:
public void showWordlist() {
edWord.setEnabled(true);
String word = edWord.getText().toString();
Uri uri = Uri.parse("content://doyle.app_name.app_ContentProvider/dict/" + mDBFile.fileName + "/list/" + word);
edWord.requestFocus();
try
{
Cursor result = getContentResolver().query(uri,null,null,null,null);
Log.i(MAIN_TAG, "Found word = " + result);
//I think the problem lies somewhere here because
//the 'result' is always 'null' (see the above log.i)
if (result != null)
{
int countRow=result.getCount();
Log.i(MAIN_TAG, "countRow = " + countRow);
mLSTCurrentWord.clear();
//mLSTCurrentContent.clear();
mLSTCurrentWordId.clear();
mAdapter.clear();
if (countRow >= 1)
{
int indexWordColumn = result.getColumnIndex("word");
int indexIdColumn = result.getColumnIndex("id");
result.moveToFirst();
String strWord;
int intId;
int i = 0;
do
{
strWord = Utility.decodeContent(result.getString(indexWordColumn));
intId = result.getInt(indexIdColumn);
mLSTCurrentWord.add(i,strWord);
mLSTCurrentWordId.add(i,intId);
//mLSTCurrentContent.add(i,strContent);
mAdapter.add(strWord);
i++;
} while (result.moveToNext());
}
result.close();
}
lstWord.setAdapter(mAdapter);
}
catch (Exception ex)
{
Log.e(MAIN_TAG, "Error = " + ex.toString());
}
edWord.setEnabled(true);
}
And here is my app_ContentProvider.
I have no idea whether there are any changes in Android 4.3 that stop my app from functioning normally.
Regarding my code lines above, can you please tell me what the problem might be? Thanks a lot.
Try set the property android:exported="true" for your content provider in your Manifest. It seems that the default value of this property has changed in android 4.3
I have a blackberry Application. It is downloaded from a web page which provides dynamic JAD file content. The JSP prints those :
out.println("Appid: " + appid);
out.println("Ip: " + user.getIp());
out.println("Servicename: " + service);
out.println("MIDlet-Version: 1.0.0");
out.println("MIDlet-Jar-URL: MyApp.jar");
out.println("MIDlet-Jar-Size: 91633");
out.println("MicroEdition-Profile: MIDP-2.0");
(and other attributes goes on like that..)
I need to get my custom attributes like "Appid" but it sometimes gets null values. User can download and run the app, but some of them cannot get my custom attributes. I dont know it is about the phone model or the current state of OS, but according to my logs, this problem appears mostly on those devices :
9800 with OS 6.0.0.546
9300 with OS 6.0.0.570
9300 with OS 6.0.0.668
9320 with OS 7.1.0.398
My code to get attributes :
CodeModuleGroup cmg = null;
CodeModuleGroup[] allGroups = CodeModuleGroupManager.loadAll();
String moduleName = ApplicationDescriptor
.currentApplicationDescriptor().getModuleName();
for (int i = 0; i < allGroups.length; i++) {
if (allGroups[i].containsModule(moduleName)) {
cmg = allGroups[i];
break;
}
}
if (cmg != null) {
AppData.firstPageURL = cmg.getProperty("Firstpage");
AppData.appId = cmg.getProperty("Appid");
AppData.firstIp = cmg.getProperty("Ip");
AppData.firstSubServiceName = cmg.getProperty("Servicename");
for (Enumeration e = cmg.getPropertyNames(); e.hasMoreElements();) {
String name = (String) e.nextElement();
String value = cmg.getProperty(name);
AppData.errorStep += "-" + name + ":" + value + "-";
}
}
By the way, I determined that the code in the for loop above never runs in these cases.
Any idea ?
Sometimes, ApplicationDescriptor.currentApplicationDescriptor().getModuleName() gives the name of the sibling cod file instead of the main cod file. So, if your module name is MyApp, the function may return MyApp-1.
To solve this, you have to strip out the number after the hyphen.
String moduleName = ApplicationDescriptor.currentApplicationDescriptor()
.getModuleName();
if(moduleName.indexOf('-') > 0) {
moduleName = moduleName.substring(0, moduleName.indexOf('-');
}