So lately I've been messing around with the idea of making my own cellphone nothing spectacular, just a basic one with touchscreen and basic functions call message calendar contacts list and the ability to connect to the internet and provide weather information via an api call..
The module Im using for gsm and GPRS communications is the popular sim900 module. I can communicate I can make calls I can do everything. But in stuck on a maybe (if not impossible to overcome) difficult roadblock.. You see sim900 module when receives a call transmits through the serial port the "RING" command followed by the "+CLIP.... (caller Id stuff)". OK I'm receiving that and I am breaking it down and accepting the command and all fine it works. But here comes the situation.. I want to read the battery capacity that is left (AT+CBC) and the gsm signal strength (AT+CSQ) all fine I'm sending those 2 commands at a fixed interval of like 3 seconds for the signal 10 for the battery. But now when a call comes it might overlap with the incoming response from trying to read the battery.. Let's say that I asked the module what is the battery level. Then the module will respond by sending "+CBC: (and battery level)" then let's say at the same exact time I receive a call.. Then all the data on the serial port just gets messed up and nothing is working.. My code is pretty rough and definitely the parsing section is awful but I'm more concerned that the parsing is not the problem. And the problem is the conflicting incoming data.. Is there any way of solving this problem? Or any other advice of where to look and how to approach the problem?
Every command from the gsm is delimited by the 0D0A sequence (CRLF)
Bellow is an example code from what i am doing
//for parsing
String incomStr;
String FirstStr;
String SecondStr;
String ThirdStr;
String FourthStr;
String FifthStr;
String SixthStr;
int strcount;
char incomChar;
boolean flagz = false;
//parsing
void getIncomingCommand() {
if (Gsm.available()) {
incomChar = Gsm.read();
//check to see if 0D0A if yes split the string
if ((incomChar == 0x0D) | flagz) {
flagz = true;
if (incomChar == 0x0A) {
switch (strcount) {
case 0:
FirstStr = incomStr;
incomStr = "";
strcount++;
flagz = false;
break;
case 1:
SecondStr = incomStr;
incomStr = "";
strcount++;
flagz = false;
break;
case 2:
ThirdStr = incomStr;
incomStr = "";
strcount++;
flagz = false;
break;
case 3:
FourthStr = incomStr;
incomStr = "";
strcount++;
flagz = false;
break;
case 4:
FifthStr = incomStr;
incomStr = "";
strcount++;
flagz = false;
break;
case 5:
SixthStr = incomStr;
incomStr = "";
strcount++;
flagz = false;
break;
default:
strcount++;
flagz = false;
incomStr = "";
}
}
} else {
incomStr += incomChar;
}
}
}
void clearIncomingCommand() {
FirstStr = "";
SecondStr = "";
ThirdStr = "";
FourthStr = "";
FifthStr = "";
SixthStr = "";
strcount = 0;
}
int getSignalLvl() {
char tempchar;
String tempstr;
Gsm.print("AT+CSQ");
Gsm.write(0x0D);
Gsm.write(0x0A);
delay(180);
while (Gsm.available()) {
tempchar = Gsm.read();
tempstr += tempchar;
}
return tempstr.substring(16, tempstr.indexOf(",")).toInt();
}
String getTime() {
char tempchar;
String tempstr;
Gsm.print("AT+CCLK?");
Gsm.write(0x0D);
Gsm.write(0x0A);
delay(180);
while (Gsm.available()) {
tempchar = Gsm.read();
tempstr += tempchar;
}
return tempstr.substring(tempstr.indexOf(",") + 1, tempstr.lastIndexOf(":"));
}
void setup() {
//start serial port
Serial.begin(115200);
//start the gsm port
Gsm.begin(9600, SERIAL_8N1, 32, 33);
strcount = 0;
updateTime(getTime());
delay(200);
updateSignal(getSignalLvl());
}
void loop() {
//stuff inside here will only be called / run only every X amount of time
// X = SECONDS/1000;
if ((millis() - lastupdate) >= 60000) {
updateTime(getTime());
lastupdate = millis();
}
getIncomingCommand();
if (SecondStr == "RING" & FourthStr.substring(0, 5) == "+CLIP") {
Serial.print("SomeOne is calling!! Number: ");
Serial.println(FourthStr.substring(8, 21));
Serial.println(phoneNums[i]);
Serial.println(FourthStr.substring(8, 21));
callerPhone = FourthStr.substring(8, 21);
clearIncomingCommand();
//important change state only once!
if (!change_state) {
came_from = state ;
change_state = 1;
}
Serial.print("coming from: ");
Serial.println(came_from);
state = 4;
flag = 0;
}
else if (SecondStr == "NO CARRIER") {
Serial.println("CALL ENDED");
clearIncomingCommand();
if (state == 3) {
state = 5;
flag = 0;
} else if (state == 4) {
state = came_from;
flag = 0;
}
change_state = 0;
}
else if (SecondStr == "MO RING") {
Serial.println("CALLING...");
clearIncomingCommand();
}
else if (SecondStr == "MO CONNECTED") {
Serial.println("CALL CONNECTED");
clearIncomingCommand();
if (state == 2) {
state = 3;
flag = 0;
}
} else if (FourthStr == "OK" | ThirdStr == "OK") {
Serial.println("Recieved ok clearing buffers");
clearIncomingCommand();
}
}
Related
Here's this code. It sort of runs but then abends. How do I make the choice work? And additionally, I wrote (copied) this code about 18 months ago, so I am vague as to why it seems so backward:
void SwitchNumber()
{
var dialogView = LayoutInflater.Inflate(Resource.Layout.list_view, null);
Android.App.AlertDialog alertDialog;
listview = dialogView.FindViewById<ListView>(Resource.Id.listview);
textview = dialogView.FindViewById<TextView>(Resource.Id.textview);
var items = new string[] { "1","2","3" };
var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, items);
using (var dialog = new Android.App.AlertDialog.Builder(this))
{
listview.Adapter = adapter;
listview.ItemClick += Listview_ItemClick;
dialog.SetTitle("Switch Number");
dialog.SetMessage("Click on the number you want to switch to");
dialog.SetView(dialogView);
string newNumber = string.Empty;
dialog.SetNegativeButton("Cancel", (s, a) => { });
dialog.SetPositiveButton("OK", (s, a) =>
{
switch (prefs.GetInt("selectitemforAlert", 0))
{
case 0:
newNumber = "1";
break;
case 1:
newNumber = "2";
break;
case 2:
newNumber = "3";
break;
default:
currentNumber = "1";
break;
}
}//switch
);
if (newNumber == currentNumber) return;
ChangeNumber(newNumber);
alertDialog = dialog.Create();
// }
}
//using
dialogView.FindViewById<ListView>(Resource.Id.listview).Adapter = adapter;
alertDialog.Show();
listview.Adapter = adapter;
listview.ItemClick += Listview_ItemClick;
}
The list does appear but I get a null object reference.
Hi I using VisualStudio 2012 and I have created web site which reads info (from .csv) from external ftp site. When I running it on local host everything works fine, but then I deployed it to azure web sites it is not working, just show zeros everywhere were should be numbers. (Dont get info from ftp)
public static List<ApiClient.Models.StatsList> GetStatsData(string Ticket, DateTime start, DateTime end, int CampaignId, String CampaignName)
{
//--------------------------------------------------------------------------------------------------------
//Gets stats from GetAdsStats service (included: Banner id, impressions, and clicks)
//--------------------------------------------------------------------------------------------------------
List<ApiClient.Models.StatsList> FullList = GetAdStatsService.GetAdsStats(Ticket, start, end, CampaignId);
List<LikesDislikesList> LikeDislike = new List<LikesDislikesList>();
//--------------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------------
string day;
string month;
if (DateTime.Today.AddDays(-1).Day.ToString().Count() == 1)
{
day = "0" + DateTime.Today.AddDays(-1).Day;
}
else
{
day = DateTime.Today.AddDays(-1).Day.ToString();
}
if (DateTime.Today.Month.ToString().Count() == 1)
{
month = "0" + DateTime.Today.Month;
}
else
{
month = DateTime.Today.Month.ToString();
}
try
{
string uri = "ftp://siteAdres" + CampaignName.Replace(" ", "_") + "_Optimizing_events_" + day + "-" + month + "-" + DateTime.Today.Year + ".csv";
Uri serverUri = new Uri(uri);
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return FullList;
}
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential("username", "password");
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader csvStream = new StreamReader(response.GetResponseStream());
//--------------------------------------------------------------------------------------------------------
//Read Likes/Dislikes from csv file stream
//--------------------------------------------------------------------------------------------------------
using (var rd = csvStream)
{
int iname = -1;
int ilikes = -1;
int idislikes = -1;
while (!rd.EndOfStream)
{
var raw = rd.ReadLine().Split((char)9);
if (rd.Peek() == -1)
{
break;
}
if (ilikes == -1 || idislikes == -1)
{
for (int i = 0; i < raw.Length; i++)
{
if (raw[i] == "Event name")
iname = i;
if (raw[i] == "Custom Event 14")
ilikes = i;
if (raw[i] == "Custom Event 15")
{
idislikes = i;
raw = rd.ReadLine().Split((char)9);
}
}
}
else
{
LikeDislike.Add(new LikesDislikesList() { Likes = Convert.ToInt32(raw[ilikes]), Dislikes = Convert.ToInt32(raw[idislikes]), Name = raw[iname] });
}
}
}
response.Close();
}
catch(Exception ex)
{
log4net.Config.XmlConfigurator.Configure();
log.Warn("GetAdStatsService.cs " + ex);
}
//--------------------------------------------------------------------------------------------------------
//Add like/dislike values for certain banners
//--------------------------------------------------------------------------------------------------------
foreach (var element in FullList)
{
foreach (var el in LikeDislike)
{
if (element.name == el.Name)
{
element.Likes = el.Likes;
element.Dislikes = el.Dislikes;
}
}
}
return FullList;
}
}
}
Check FtpWebResponse.StatusCode before calling response.GetResponseStream(). You are probably having come kind of connection error. My guess would be firewall settings on your Azure VM.
i'm trying to make an app that can create a list of available wifi access point. here's part of the code i used:
x = new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
if (results != null) {
for (int i=0; i<size; i++){
ScanResult scanresult = wifi.getScanResults().get(i);
String ssid = scanresult.SSID;
int rssi = scanresult.level;
String rssiString = String.valueOf(rssi);
textStatus.append(ssid + "," + rssiString);
textStatus.append("\n");
}
unregisterReceiver(x); //stops the continuous scan
textState.setText("Scanning complete!");
} else {
unregisterReceiver(x);
textState.setText("Nothing is found. Please make sure you are under any wifi coverage");
}
}
};
both textStatus and textState is a TextView.
i can get this to work but sometimes the result shows duplicate SSID but with different signal level, in a single scan. there might be 3-4 same SSIDs but with different signal level.
is it really different SSIDs and what differs them? can anyone explain?
Are you having several router modems for the same network? For example: A company has a big wireless network with multiple router modems installed in several places so every room has Wifi. If you do that scan you will get a lot of results with the same SSIDs but with different acces points, and thus different signal level.
EDIT:
According to Walt's comment you can also have multiple results despite having only one access point if your modem is dual-band.
use below code to to remove duplicate ssids with highest signal strength
public void onReceive(Context c, Intent intent) {
ArrayList<ScanResult> mItems = new ArrayList<>();
List<ScanResult> results = wifiManager.getScanResults();
wifiListAdapter = new WifiListAdapter(ConnectToInternetActivity.this, mItems);
lv.setAdapter(wifiListAdapter);
int size = results.size();
HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
try {
for (int i = 0; i < size; i++) {
ScanResult result = results.get(i);
if (!result.SSID.isEmpty()) {
String key = result.SSID + " "
+ result.capabilities;
if (!signalStrength.containsKey(key)) {
signalStrength.put(key, i);
mItems.add(result);
wifiListAdapter.notifyDataSetChanged();
} else {
int position = signalStrength.get(key);
ScanResult updateItem = mItems.get(position);
if (calculateSignalStength(wifiManager, updateItem.level) >
calculateSignalStength(wifiManager, result.level)) {
mItems.set(position, updateItem);
wifiListAdapter.notifyDataSetChanged();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is my simple Solution please and it is work for me
private void scanWifiListNew() {
wifiManager.startScan();
List<ScanResult> wifiList = wifiManager.getScanResults();
mWiFiList = new ArrayList<>();
for(ScanResult result: wifiList){
checkItemExists(mWiFiList, result);
}
setAdapter(mWiFiList);
}
private void printList(List<ScanResult> list){
for(ScanResult result: list){
int level = WifiManager.calculateSignalLevel(result.level, 100);
System.out.println(result.SSID + " Level is " + level + " out of 100");
}
}
private void checkItemExists(List<ScanResult> newWiFiList, ScanResult resultNew){
int indexToRemove = -1;
if(newWiFiList.size() > 0) {
for (int i = 0; i < newWiFiList.size(); i++) {
ScanResult resultCurrent = newWiFiList.get(i);
if (resultCurrent.SSID.equals(resultNew.SSID)) {
int levelCurrent = WifiManager.calculateSignalLevel(resultCurrent.level, 100);
int levelNew = WifiManager.calculateSignalLevel(resultNew.level, 100);
if (levelNew > levelCurrent) {
indexToRemove = i;
break;
}else indexToRemove = -2;
}
}
if(indexToRemove > -1){
newWiFiList.remove(indexToRemove);
newWiFiList.add(indexToRemove,resultNew);
}else if(indexToRemove == -1)newWiFiList.add(resultNew);
} else newWiFiList.add(resultNew);
}
private void setAdapter(List<ScanResult> list) {
listAdapter = new WifiListAdapter(getActivity().getApplicationContext(), list);
wifiListView.setAdapter(listAdapter);
}
Hi am trying to run my app on blackberry device using Edge gprs connection but its not rendering the pages.i have tried lot to get the connection,also i tried the various links to solve, one of the simple code i have attached here, kindly guide me to solve this
public static String getConnectionString() {
String value="" ;
if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
value=";interface=wifi";
}else{
value=";deviceside=true";
}
return value;
}
Append the connection string to your url. Then try
public static String getConnectionString() {
// This code is based on the connection code developed by Mike Nelson of
// AccelGolf.
// http://blog.accelgolf.com/2009/05/22/blackberry-cross-carrier-and-cross-network-http-connection
String connectionString = null;
// Simulator behavior is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceSide=true";
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
// System.out.println("Device is connected via Wifi.");
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// System.out.println("Carrier coverage.---->>" + CoverageInfo.getCoverageStatus());
String carrierUid = getCarrierBIBSUid();
// DebugScreen.Log(" carrierUid is: " + carrierUid);
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
// System.out.println("No Uid");
String wapString = getAvailableConnectionsString();
// DebugScreen.Log("from wap2 connection--->" + wapString);
if(wapString == null){
connectionString = ";deviceside=true";
}else{
connectionString = wapString;
}
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=true;connectionUID=" + carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// System.out.println("MDS coverage found");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
// System.out.println("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be reachable.
else {
// System.out.println("no other options found, assuming device.");
connectionString = ";deviceside=true";
}
return connectionString;
}
Add this method and append connection String to url.
private static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
// DebugScreen.Log("Util.getCarrierBIBSUid() for ippp--------->>" + records[currentRecord].getCid().toLowerCase());
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
// DebugScreen.Log("Util.getCarrierBIBSUid() for bibs..........'''''" + records[currentRecord].getName().toLowerCase().indexOf("bibs") );
if (records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
public static String getAvailableConnectionsString() {
String conns = null;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
String cid;
String uid;
for (int i = 0; i < records.length; i++) {
ServiceRecord myRecord = records[i];
// System.out.println("record name:"+myRecord.getName()+" cid:"+myRecord.getCid().toLowerCase()+" "+myRecord.getUid().toLowerCase());
if (myRecord.isValid() && !myRecord.isDisabled()) {
cid = myRecord.getCid().toLowerCase();
uid = myRecord.getUid().toLowerCase();
//Wap2.0
if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1 && uid.indexOf("mms") == -1 ) {
conns = ";deviceside=true" + ";ConnectionUID="+ myRecord.getUid();
if(myRecord.getUid().equalsIgnoreCase("GTCP BIBS")){
return conns;
}
}
}
}
return conns;
}
This code is work for me..
When I run this application on a device using the WiFi
it's working fine. But when I am using a mobile network or 3g it's giving an error.
It's not working on the mobile network.
I am using this code:
connection = (HttpConnection) Connector.open(APIURL+ updateConnectionSuffix());
And my ConnectionTools class code:
public String updateConnectionSuffix() {
String connSuffix;
if (DeviceInfo.isSimulator()) {
connSuffix = ";deviceside=true";
} else if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
&& RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
connSuffix = ";interface=wifi";
} else {
String uid = null;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
for (int i = 0; i < records.length; i++) {
if (records[i].isValid() && !records[i].isDisabled()) {
if (records[i].getUid() != null
&& records[i].getUid().length() != 0) {
if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1)
&& (records[i].getUid().toLowerCase().indexOf(
"wifi") == -1)
&& (records[i].getUid().toLowerCase().indexOf(
"mms") == -1)) {
uid = records[i].getUid();
break;
}
}
}
}
if (uid != null) {
// WAP2 Connection
connSuffix = ";ConnectionUID=" + uid;
} else {
connSuffix = ";deviceside=true";
}
}
return connSuffix;
}
Can you give me any solutions?
What should we do for the mobile network or 3g?
Try this code.
public static String getConnectionString() {
String connectionString = null;
// Simulator behaviour is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceside=true";
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid hassling the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
connectionString = "none";
}
// In theory, all bases are covered by now so this shouldn't be reachable.But hey, just in case ...
else {
connectionString = ";deviceside=true";
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*/
private synchronized static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
Replace this function by your updateConnectionSuffix().
Let me explain : - This is for connection using mobile network 2g or 3g any network" just copy & paste & enjoy
String url = "vm.b24esolution.com:9090";
final HttpConnection connection = (HttpConnection) Connector.open("socket://"+url+updateConnectionSuffix()+";apn=rim.net.gprs;tunnelauthusername =;tunnelauthpassword=",Connector.READ_WRITE);