Device integration using MQTT - cumulocity

Hello I am new to cumulocity and need help for the following scenarios
I am trying to create a child device with following code:
public static void main(String[] args) {
final MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setUserName(TENANT + "/" + USERNAME);
connOpts.setPassword(PASSWORD.toCharArray());
final MqttClient client;
try {
client = new MqttClient(SERVERURL, CLIENTID, null);
client.connect(connOpts);
client.publish("s/us", ("100," + DEVICE_NAME + ",c8y_MQTTDevice").getBytes(), 2, false);
// set device's hardware information
client.publish("s/us", "110,101010203,MQTT test model,Rev0.1".getBytes(), 2, false);
//create Child device
client.publish("s/us", ("101, 9999,ivelin13, c8y_MQTTChildDevice").getBytes(), 2, false);
} catch (
MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The above code creates child device but i want to set it- hardware information. The template for that operation is
110,serialNumber,hardwareModel,revision
But i could not find how to set hardware information on the current child device. Maybe i have to select that child device- but i don't know how?
Also i want to sent temperature measurement to the current child device. How do I select a child device?
Thanks in advance

If you want to send a command to a child device, you can just add the child device's ID to the message's topic. In both example cases (setting hardware information and adding measurements), you have to publish your message to the topic s/us/9999.
[Edit] Example code:
string registerTopic = "s/us/" + parentId; }
await mqtt.PublishAsync(registerTopic, $"101,{childId},{deviceName},{deviceType}").ConfigureAwait(false);
string configTopic = "s/us/" + childId;
await mqtt.PublishAsync(configTopic, $"114,c8y_Command").ConfigureAwait(false);
await mqtt.PublishAsync(configTopic, $"117,11").ConfigureAwait(false);

Related

How to fetch all the fields from ServiceFeatureTable in arcgis

I am using arcgis library 100.0.0 in android for displaying maps and information inside map.
I am using the following code to populate a ServiceFeaturetable using URL provided by arcGis. I am able to load the feature layer successfully into the mapview. I have written code that listens to the click on the symbol on the map, so that I can get some information about the specific feature on the map. I am able to get the specific feature OnClick.
Upon investigating the GetAttributes() result of the specific feature, I realize that it is not having all the fields. After investigating on internet, I found that the FeatureTable.QueryFeaturesAsync could be used to get all the fields of the feature. Even though I have written the code to get all the fields, I do not know how I link this result with the feature layer, so that the feature has all the fields that I require. Here is the code
final ServiceFeatureTable serviceFeatureTable = new ServiceFeatureTable("some URL");
ListenableFuture<FeatureQueryResult> queryresult = serviceFeatureTable.queryFeaturesAsync(null, ServiceFeatureTable.QueryFeatureFields.LOAD_ALL);
// create the feature layer using the service feature table
final FeatureLayer featureLayer = new FeatureLayer(serviceFeatureTable);
featureLayer.setSelectionColor(Color.YELLOW);
featureLayer.setSelectionWidth(10);
// add the layer to the map
mapView.getMap().getOperationalLayers().add(featureLayer);
// set an on touch listener to listen for click events
mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(getContext(), mapView) {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// get the point that was clicked and convert it to a point in map coordinates
Point clickPoint = mMapView.screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));
int tolerance = 10;
double mapTolerance = tolerance * mMapView.getUnitsPerDensityIndependentPixel();
// create objects required to do a selection with a query
Envelope envelope = new Envelope(clickPoint.getX() - mapTolerance, clickPoint.getY() - mapTolerance, clickPoint.getX() + mapTolerance, clickPoint.getY() + mapTolerance, mapView.getMap().getSpatialReference());
QueryParameters query = new QueryParameters();
query.setGeometry(envelope);
// call select features
final ListenableFuture<FeatureQueryResult> future = featureLayer.selectFeaturesAsync(query, FeatureLayer.SelectionMode.NEW);
// add done loading listener to fire when the selection returns
future.addDoneListener(new Runnable() {
#Override
public void run() {
try {
//call get on the future to get the result
FeatureQueryResult result = future.get();
// create an Iterator
Iterator<Feature> iterator = result.iterator();
Feature feature;
// cycle through selections
int counter = 0;
while (iterator.hasNext()){
feature = iterator.next();
counter++;
String name = feature.getAttributes().get(Constants.FIELD_NAME).toString();
Log.d(getResources().getString(R.string.app_name), "Selection #: " + counter + " Table name: " + feature.getFeatureTable().getTableName());
}
//Toast.makeText(getApplicationContext(), counter + " features selected", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e(getResources().getString(R.string.app_name), "Select feature failed: " + e.getMessage());
}
}
});
return super.onSingleTapConfirmed(e);
}
});
Try replacing your code
from
final ListenableFuture<FeatureQueryResult> future = featureLayer.selectFeaturesAsync(query, FeatureLayer.SelectionMode.NEW);
to
final ListenableFuture<FeatureQueryResult> future = serviceFeatureTable.queryFeaturesAsync(query, ServiceFeatureTable.QueryFeatureFields.LOAD_ALL);
It works for me!

How i can sing up with restcomm correctly?

Already few weeks i try sing up on SIP service with restcomm for android. I check connection with third-party application (cSipSimple) and everything works correctly. But when i try coonection with restcomm demo app, connection falls everytime after 4 seconds. Whats wrong with my sdk or how i can sing up right?
SipProfile sipProfile = new SipProfile();
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("pref_proxy_ip", "my.server.ip");
params.put("pref_proxy_port", "5060");
params.put("pref_sip_user", "7879114");
params.put("pref_sip_password", "EeFei2Fa");
for (String key : params.keySet()) {
if (key.equals("pref_proxy_ip")) {
sipProfile.setRemoteIp((String) params.get(key));
} else if (key.equals("pref_proxy_port")) {
sipProfile.setRemotePort(Integer.parseInt((String) params.get(key)));
} else if (key.equals("pref_sip_user")) {
sipProfile.setSipUserName((String) params.get(key));
} else if (key.equals("pref_sip_password")) {
sipProfile.setSipPassword((String) params.get(key));
}
}
final SipManager sipManager = new SipManager(sipProfile, true);
Register registerRequest = new Register();
final Request r = registerRequest.MakeRequest(sipManager, 100000, null);
// Send the request statefully, through the client transaction.
Thread thread = new Thread() {
public void run() {
try {
final ClientTransaction transaction = sipManager.sipProvider.getNewClientTransaction(r);
transaction.sendRequest();
} catch (SipException e) {
e.printStackTrace();
}
}
};
thread.start();
#Vladislav, you are using the low level facilities of the SDK which are obsolete and not meant to be used directly. I would suggest that you use the RestCommClient API as exposed by the SDK directly. It is much easier to use and provides the same functionality and more.
For an example on how to use it please check:
https://github.com/RestComm/restcomm-android-sdk/blob/master/Examples/restcomm-helloworld/app/src/main/java/com/telestax/restcomm_helloworld/MainActivity.java
You need to change the SIP server settings from:
https://github.com/RestComm/restcomm-android-sdk/blob/master/Examples/restcomm-helloworld/app/src/main/java/com/telestax/restcomm_helloworld/MainActivity.java#L99
And the called party from:
https://github.com/RestComm/restcomm-android-sdk/blob/master/Examples/restcomm-helloworld/app/src/main/java/com/telestax/restcomm_helloworld/MainActivity.java#L174
Just keep in mind that for media Webrtc is used so that NATs can be handled properly. This means that the receiving party needs to be able to handle Webrtc as well. Unless there's a server in the middle handling the mediation, like Restcomm-Connect.
For more information please check RestComm Client Android SDK Quick Start

How to set the name of a snapshot file

I am developing a J2ME application to run on my W595s Sony Ericsson mobile phone.
My application uses the JSR 135 Mobile Media API and the JSR 234 Advanced Multimedia Supplements API.
My application displays a Form.
The camera video is displayed in a Form's item.
The Form has a command.
The application takes a snapshot when the user activates the command.
The snapshot file is saved to the Picture directory on the memory stick.
Here is the Form's commandAction event listener :
public void commandAction(Command arg0, Displayable arg1) {
m_snapshotControl.setDirectory("e:/Picture");
m_snapshotControl.setFilePrefix("AC");
m_snapshotControl.setFileSuffix(".JPG");
int[]resolutions = m_cameraControl.getSupportedStillResolutions();
int maxValue = (resolutions.length / 2) - 1;
m_cameraControl.setStillResolution(maxValue);
m_snapshotControl.start(1);
}
I ran my application 2 times.
The Picture directory did not contain any snapshot file before the first run.
I did the following actions during each run :
I activated the command
I answered yes to the following rights requesting dialogs :
Allow the application to read user data ?
Allow the application to write user data ?
Allow the application to read user data ?
Allow the application to write user data ?
Allow the application to shoot with the camera ?
Allow the application to read user data ?
Allow the application to write user data ?
The AC0000.jpg snapshot file was created after the first run.
The AC0000.jpg picture file was replaced after the second run.
I do not want my application to replace snapshots taken during past runs.
How can I set the name of a snapshot file before taking the snapshot ?
Is it possible to set the string in between the prefix and the suffix ?
Any help will be greatly appreciated
I haven't tried on this particular range of phone but how about this:
private int iSnapshotCounter = 0;
public void commandAction(Command arg0, Displayable arg1) {
m_snapshotControl.setDirectory("e:/Picture");
m_snapshotControl.setFilePrefix("AC");
m_snapshotControl.setFileSuffix( (++iSnapshotCounter) + ".JPG");
int[]resolutions = m_cameraControl.getSupportedStillResolutions();
int maxValue = (resolutions.length / 2) - 1;
m_cameraControl.setStillResolution(maxValue);
m_snapshotControl.start(1);
}
If that works, you can then decide to include the date and time (say, to the second) in the file name.
Of course, if setFileSuffix() won't allow you to specify more than a file extension, you can try to use the same trick on the prefix string.
You may also need to use JSR-75 to figure out what files already exist in the folder.
I have added a PlayerListener to the SnapshotControl's Player.
My playerUpdate method renames the created Snapshot file when the SHOOTING_STOPPED event occurs.
The new name is made up of the current date and time's parts.
The format of the new name is YYYYMMDD_HHMMSS.jpg.
Here is the playerUpdate method :
public void playerUpdate(Player arg0, String arg1, Object arg2) {
if (arg1.equalsIgnoreCase(SnapshotControl.SHOOTING_STOPPED)) {
FileConnection fconn = null;
try {
fconn = (FileConnection)Connector.open("file:///e:/Picture/" + (String)arg2);
Date now = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
StringBuffer buffer = new StringBuffer();
buffer.append(calendar.get(Calendar.YEAR));
int month = calendar.get(Calendar.MONTH);
month++;
if (month < 10) {
buffer.append(0);
}
buffer.append(month);
int day = calendar.get(Calendar.DAY_OF_MONTH);
if (day < 10) {
buffer.append(0);
}
buffer.append(day);
buffer.append("_");
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour < 10) {
buffer.append(0);
}
buffer.append(hour);
int minute = calendar.get(Calendar.MINUTE);
if (minute < 10) {
buffer.append(0);
}
buffer.append(minute);
int second = calendar.get(Calendar.SECOND);
if (second < 10) {
buffer.append(0);
}
buffer.append(second);
buffer.append(".jpg");
fconn.rename(buffer.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fconn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Why I'm getting all history revisions when querying for Iterations or Releases?

I'm working with Rally REST API for Java
I want get the list of actual Iterations and Releases
here is the snippet
JsonObject projects = new JsonObject();
QueryRequest queryProjects = new QueryRequest("release");
queryProjects.setPageSize(1);
queryProjects.setLimit(1000);
queryProjects.setFetch(new Fetch("_refObjectName","Name"));
QueryResponse queryResponse;
try {
queryResponse = restApi.query(queryProjects);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new ServiceException(e);
}
In result I'm getting the list with a lot of duplicates. After closer inspection it seems I'm getting all versions of object - for the same Iteration/Release I have multiple versions - I can see different "_objectVersion" attribute for such duplicates.
Why is it so?
Can you please help me with the query which will retrieve distinct list of Iterations / Releases - I'm interested in just latest versions.
I can filter it out in Java but have a feeling there is more 'proper' way of doing this. Also getting the list with whole object history is not the best for code performance.
Thanks for any help!
When Releases and Iterations are created in Rally in a top project there is an option to propagate them throughout the project hierarchy. For example, if you have top project P1 with child project P2 and grandchild projects P21 and P22, you may create 4 releases with the same name and the same start and release dates. They are not identical releases: they have ObjectID and _ref unique to them. Please verify if this applies to your scenario.
To limit release query to a specific project set request project. Here is an example that returns only three releases that I have in a top project: R1,R2, and R3. Note
String projectRef = "/project/12352608219";
that is used later in the code:
releaseRequest.setProject(projectRef);
Note also the commented out
//String workspaceRef = "/workspace/12352608129";
and
// releaseRequest.setWorkspace(workspaceRef);
If I switch the comments: comment out project reference and uncomment workspace reference I will get what you called duplicates: multiple R1, R2 and R3 releases.
public class FindReleases {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String username = "user#co.com";
String password = "secret";
String projectRef = "/project/12352608219";
//String workspaceRef = "/workspace/12352608129";
String applicationName = "RESTExampleFindReleasesByProject";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
System.out.println(restApi.getWsapiVersion()); //v.2.0 by default when using 2.0.2 jar and up
QueryRequest releaseRequest = new QueryRequest("Release");
releaseRequest.setFetch(new Fetch("Name"));
releaseRequest.setLimit(1000);
releaseRequest.setScopedDown(false);
releaseRequest.setScopedUp(false);
// releaseRequest.setWorkspace(workspaceRef);
releaseRequest.setProject(projectRef);
QueryResponse releaseQueryResponse = restApi.query(releaseRequest);
int numberOfReleasesInProject = releaseQueryResponse.getTotalResultCount();
System.out.println(numberOfReleasesInProject);
if(numberOfReleasesInProject >0){
for (int i=0;i<numberOfReleasesInProject;i++){
JsonObject releaseJsonObject = releaseQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println(releaseJsonObject.get("Name"));
}
}
}
finally{
if (restApi != null) {
restApi.close();
}
}
}
}

Parse Push Notfications in MonoDroid

So I'm using the Parse component from the Xamarin store in my MonoDroid app. So I was able to use the following code to store an object
ParseClient.Initialize ("appid", "windowskey");
var obj = new ParseObject("Note");
obj ["text"] = "Hello, world! This is a Xamarin app using Parse!";
obj ["tags"] = new List<string> {"welcome", "xamarin", "parse"};
obj.SaveAsync ();
My real goal is to be able to do push notifications. Even though the above object stored, Parse did not register the device in the installations to be able to send push notifications. What else am I missing. Note: I'm doing this in the emulator but if i'm not mistaken it still should work.
#basit-zia, yes I did! I had to create a binding for the push library from the Java Parse SDK. I believe I was able to strip away all the libraries except for the necessary elements. I can't remember exactly what I did though.
Then in the Main Activity class, I put the following into the OnStart() method:
// check for a notification
if (Intent != null)
try {
string jsonString = Intent.Extras.GetString("com.parse.Data");
PushObject jsonObj = JsonConvert.DeserializeObject<PushObject>(jsonString);
if (jsonObj.alert != null) {
Toast.MakeText (BaseContext, jsonObj.alert, ToastLength.Long).Show ();
}
} catch (Exception e) {
Console.WriteLine ("JSONException: " + e.Message);
}
And put the following into the OnCreate() method:
Com.Parse.Parse.Initialize(this, "app id here"}, "client key here");
PushService.SetDefaultPushCallback (this, this.Class);
PushService.StartServiceIfRequired (this);
ParseInstallation.CurrentInstallation.SaveInBackground ();