I am working on a project where I need to read and write data from a particular column and a row from Azure Mobile Services to an Arduino. Simply, I need to read and write data to an azure mobile service by an Arduino. The writing part is pretty much done but I am facing a bit of problem in reading the data.
Here is my scenario
1: Upload sensor data from Arduino to Azure mobile service (completed almost)
2: Develop an windows phone app to access the data from azure mobile service (competed)
3: Develop an windows phone app to write data to the azure table(completed)
4: Use the data written in the above step to control my Arduino (STUCK)
Any help will be appreciated.
Assuming you have an HTTP client to do REST on your Arduino, you could do something like the following:
String read(String table) {
HttpClient http;
http_header_t headers[] = {
{ "X-ZUMO-APPLICATION", "applicationKeyHere" },
{ "Content-Type", "application/json" },
{ NULL, NULL } // NOTE: Always terminate headers with NULL
};
http_request_t request;
http_response_t response;
request.hostname = "mobileservicename.azure-mobile.net";
request.port = 80;
request.path = "/tables/" + table; //update with your table name
http.get(request, response, headers);
return response.body;
}
Related
Using the Local Home SDK developer preview for Google Assistant, I'm receiving a TypeError from my application during IDENTIFY that was previously working correctly. The error is claiming that UdpScanData is not a valid string when I try to decode the payload.
Example code:
const device = identifyRequest.inputs[0].payload.device;
const response = Buffer.from(device.udpScanData, "hex");
How do I access the UDP discovery payload?
In the 0.2.0 update to the developer preview SDK, we have migrated the UdpScanData parameter to be an interface instead of just a type alias for string (see the updated reference docs) to improve consistency with the other scan data types.
To access the response payload for a UDP scan in the latest SDK, update your package.json dependencies to use v0.2.0:
{
...
"dependencies": {
"#google/local-home-sdk": "^0.2.0"
}
}
Then, access the payload using the new data property:
const device = identifyRequest.inputs[0].payload.device;
const scanData = device.udpScanData;
const response = Buffer.from(scanData.data, "hex");
I have been asked by a developer (Cold Fusion) to expose the REST API so they can programatically create Work Items from a in house developed application.
This is my first foray into REST within TFS and I am not to sure where to start. I checked the Microsoft documentation but it is of course biased towards .NET or client libraries, but as far as I can make out I wont be able to do anything with these as it is cold fusion environment making the "call" ?
Can I get some advice as to how I go about achieving this?
Representational State Transfer (REST) APIs are service endpoints that support sets of HTTP operations (methods), which provide create, retrieve, update, or delete access to the service's resources.
The Api to create a work item is as below:
POST https://{accountName}.visualstudio.com/{project}/_apis/wit/workitems/${type}?api-version=4.1
[
{
"op": "add",
"path": "/fields/System.Title",
"from": null,
"value": "Sample task"
}
]
If you just want to test the rest api, you could download Postman, and test api using it. If you want to use the rest api in the code, you could refer to the example below.
Here is an example getting a list of projects for your account:
using System.Net.Http;
using System.Net.Http.Headers;
...
//encode your personal access token
string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalAccessToken)));
ListofProjectsResponse.Projects viewModel = null;
//use the httpclient
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://{accountname}.visualstudio.com"); //url of our account
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
//connect to the REST endpoint
HttpResponseMessage response = client.GetAsync("_apis/projects?stateFilter=All&api-version=1.0").Result;
//check to see if we have a succesfull respond
if (response.IsSuccessStatusCode)
{
//set the viewmodel from the content in the response
viewModel = response.Content.ReadAsAsync<ListofProjectsResponse.Projects>().Result;
//var value = response.Content.ReadAsStringAsync().Result;
}
}
Useful links:
https://learn.microsoft.com/en-us/rest/api/vsts/?view=vsts-rest-4.1
https://learn.microsoft.com/en-us/rest/api/vsts/wit/work%20items/create?view=vsts-rest-4.1
I am trying to use Azure Iot hub REST API to create device by following links
Create a new device identity
Control access to IoT Hub
And my http data is like
{
"status":"connected",
"authentication":{ "symmetricKey":{
"primaryKey":"key in shared access policies",
"secondaryKey":"key in shared access policies"}
},
"statusReason":"reason",
"deviceId":"test123"
}
My header is like
["Content-Type": "application/json", "Authorization": "SharedAccessSignature sig=(key in shared access policies public key)=&se=1481687791&skn=iothubowner&sr=(my iot hub name).azure-devices.net%2fdevices%2ftest123"]
But i get error 401
{"Message":"ErrorCode:IotHubUnauthorizedAccess;Unauthorized","ExceptionMessage":"Tracking ID:(tracking id )-TimeStamp:12/14/2016 03:15:17"}
Anyone know how to fixed it , or to track the exceptionMessage ?
The problem of 401 is, probably, in the way you are calculating the SAS.
The full process to calculate a SAS for the IoT Hub (in C#) is:
private static readonly DateTime epochTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
public static string SharedAccessSignature(string hostUrl, string policyName, string policyAccessKey, TimeSpan timeToLive)
{
if (string.IsNullOrWhiteSpace(hostUrl))
{
throw new ArgumentNullException(nameof(hostUrl));
}
var expires = Convert.ToInt64(DateTime.UtcNow.Add(timeToLive).Subtract(epochTime).TotalSeconds).ToString(CultureInfo.InvariantCulture);
var resourceUri = WebUtility.UrlEncode(hostUrl.ToLowerInvariant());
var toSign = string.Concat(resourceUri, "\n", expires);
var signed = Sign(toSign, policyAccessKey);
var sb = new StringBuilder();
sb.Append("sr=").Append(resourceUri)
.Append("&sig=").Append(WebUtility.UrlEncode(signed))
.Append("&se=").Append(expires);
if (!string.IsNullOrEmpty(policyName))
{
sb.Append("&skn=").Append(WebUtility.UrlEncode(policyName));
}
return sb.ToString();
}
private static string Sign(string requestString, string key)
{
using (var hmacshA256 = new HMACSHA256(Convert.FromBase64String(key)))
{
var hash = hmacshA256.ComputeHash(Encoding.UTF8.GetBytes(requestString));
return Convert.ToBase64String(hash);
}
}
If you want to create the device in the IoTHub you have to have a policy with full permissions that mean:
Registry read and write, Service connect and Device connect.
If you need a full functional example, in C#, about how use the IoT Hub REST API to create a device, check if a device exists and send messages to the IoT Hub I have wrote this post about it (the post is in spanish but I can imagine that what you need is just the code).
it looks like your SAS is wrong. It shouldn't include the devices part in the end. If you open the Iot Hub Device Explorer you can Generate SAS token to access the Iot Hub API. You should create the SAS for the IoT hub level and for a device level (which include the devive id in the SAS like you have).
So your SAS should look like this -
SharedAccessSignature sr={iot hub name}.azure-devices.net&sig={sig}&se={se}&skn=iothubowner
There are two edits you need to do:
In your http data, only deviceId is required, other are optional, you can do it like this:
{
deviceId: "test123"
}
Note that there are no double quotes around deviceId.
Like #shachar said, you need remove "%2fdevices%2ftest123" in SAS token of the header. About generating SAS token you can utilize Device Explorer.
This is my test result:
The format of SAS token you use is wrong. To create a device, you need to use SAS Token for IoT Hub. You could easily use Azure IoT Toolkit extension for Visual Studio Code to generate SAS Token for IoT Hub as below screenshot.
BTW, the format of SAS token for device is /^SharedAccessSignature sr=iot-hub-test.azure-devices.net%2Fdevices%2Fdevice1&sig=.+&se=.+$/, while the format of SAS token for IoT Hub is /^SharedAccessSignature sr=iot-hub-test.azure-devices.net&sig=.+&skn=iothubowner&se=.+$/
//Following code is to generate the SAS token programatically.
string sasToken = new SharedAccessSignatureBuilder()
{ KeyName = name,
Key = key,
Target = target,
TimeToLive = TimeSpan.FromDays(days)
}.ToSignature();
//use this sas token as authorization header before calling the iot restapi
For the past 3 years we have used HTML/Js only with Firebase but now we are using Unity as well.
The current Unity/Firebase only works on Android/iOS when deployed and 99% of our work is on the windows store.
I've actually got a pretty decent Unity/Firebase codebase going but it requires me to use a full App Secret.
All the other libraries expose a method to login with Email/Password but the REST API only allows the use of a token or your app secret that it then states is ill advised to put into your client; I guess the thinking is if you're using a different library that you'll have your own auth/user method which we don't...
Now, I've pulled apart the web version and got this:
https://auth.firebase.com/v2/<myfirebase>/auth/password?&email=dennis%40<mysite>&password=<mypassword>v=js-2.2.9&transport=json&suppress_status_codes=true
So there IS an endpoint that I can send stuff to and I've tested it inside unity with good results.
Obviously the URL isn't guaranteed to stay working but I'm wondering if there is any reason NOT to use this?
Also, Why not just expose this endpoint in the official REST API?
As I understand it, that URL will continue to work for your Legacy Firebase project. You will have to do the same sort of reverse engineering if you want to update to the new Firebase 3.0 API. However, if you are still using a legacy Firebase project -- I encourage you to take a look at this. It has not been updated to work with Firebase 3.0 -- so I needed to do something similar to what you did to allow login to the new API.
I was able to do this with the new API using C# as follows (where FirebaseManager is a Singleton I wrote for Global variables and functions to write and read from/to the DB :
Hashtable loginData = new Hashtable();
loginData.Add ("email", <EMAIL-GOES-HERE>);
loginData.Add ("password", <PASSWORD-GOES-HERE>);
loginData.Add ("returnSecureToken", true);
UnityHTTP.Request loginRequest = new UnityHTTP.Request ("post",
"https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key="
+ <YOUR-PROJECT-API-KEY-GOES-HERE>, loginData);
loginRequest.Send ((request) => {
Hashtable jsonResponse = (Hashtable)JSON.JsonDecode(request.response.Text);
if (jsonResponse == null) {
DisplayErrorMessage("Error logging in. Server returned null or malformed response");
}
FirebaseManager.Instance.idToken = (string)jsonResponse["idToken"]; // This is your auth token
FirebaseManager.Instance.uid = (string)jsonResponse["localId"]; // this is your "uid"
});
// I have a list of users in my db keyed by the "uid" -- I access them like this
UnityHTTP.Request fullnameRequest = new UnityHTTP.Request ("get",
<YOUR-DATABASE-ROOT-URL-HERE>
+ "/users/" + FirebaseManager.Instance.uid + ".json?auth=" + FirebaseManager.Instance.idToken);
fullnameRequest.Send ((request) => {
Debug.Log(request.response.Text);
Hashtable jsonResponse = (Hashtable)JSON.JsonDecode(request.response.Text);
if (jsonResponse == null) {
DisplayErrorMessage("Error getting user info. Server returned null or malformed response");
}
FirebaseManager.Instance.fullname = (string)jsonResponse["fullname"];
FirebaseManager.Instance.groupId = (string)jsonResponse["group"]; // just storing this in memory
});
So I don't think there is any harm in using the URL, just make sure you budget time for more work when things change.
i'm developing a mobile project the can control a home an receve information from it either from inside or outside of the house. im setting up a port forwarding mechanism on my router to connect to my server if i'm using my application from the outside.
i think that the fact of receving data from the server should be initiated by the client (android app) witch is in an other notwork or it will be blocked.
* is there a solution to receve data (temperature) in real time from the outside simply by just requesting once or i should send a request like evrey minute? * i'm confused because some applications like video streaming receve data from servers by just starting the video player then it receve udp packets automaticly
more spicificlly can i send data from a server to a distant client by just sending a request once (maybe by letting the socket open for every client, VPN , SIP)???
Sending Data to Distant Clients: Securely & Reliably
There is only one reasonably-reliable method for sending a signal to distant clients. I want to confirm your original assumption of sending to clients without request, this is theoretically impossible as the device needs to call home somewhere and notify a broker gateway (SIP) or otherwise of it's address. However please ignore that because the right way will be relayed here with source code.
Security Importance
It is important to realize that opening your firewall is outside of good practices. It is better to hold onto the firewall's lockdown rules for inbound traffic. The following section is a secure method that will allow you to open an outbound connection with maximum security preventing snooping and other unsafe security holes.
Download Android Source Libraries
See instructions here for downloading Android Source Library Files: https://github.com/pubnub/java/tree/master/android
Receiving Data On-Demand from a Distance on Android
You'll need to copy/paste the following code to get things moving forward quickly. Start by taking this Java code and pasting it into your app. Then follow by downloading the library files.
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// ANDROID PHONE
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Pubnub pubnub = new Pubnub(
"", // PUBLISH_KEY (Optional, supply "" to disable)
"demo", // SUBSCRIBE_KEY (REQUIRED)
"", // SECRET_KEY (Optional, supply "" to disable)
"", // CIPHER_KEY (Optional, supply "" to disable)
true // SSL_ON?
);
Hashtable args = new Hashtable(1);
args.put( "channel", "distant-client-ABC-DEF" );
pubnub.subscribe(args, new Callback() {
public void connectCallback(String channel) {
System.out.println("CONNECT on channel:" + channel);
}
public void disconnectCallback(String channel) {
System.out.println("DISCONNECT on channel:" + channel);
}
public void reconnectCallback(String channel) {
System.out.println("RECONNECT on channel:" + channel);
}
public void successCallback(String channel, Object message) {
System.out.println(channel + " " + message.toString());
}
public void errorCallback(String channel, Object message) {
System.out.println(channel + " " + message.toString());
}
});
Send Data On-demand to the Distant Client
On a Java VM on your home computer/systems, you may use the same code to send data securely to the remote distant client. Use the following code to do this:
Download JVM Server Source Libraries
See instructions here for downloading/using JVM Server Source Library Files: https://github.com/pubnub/java/tree/master/java
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// HOME SERVER
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Pubnub pubnub = new Pubnub(
"demo", // PUBLISH_KEY (REQUIRED on Server)
"demo", // SUBSCRIBE_KEY (REQUIRED)
"", // SECRET_KEY (Optional, supply "" to disable)
"", // CIPHER_KEY (Optional, supply "" to disable)
true // SSL_ON?
);
Hashtable args = new Hashtable(1);
args.put( "channel", "distant-client-ABC-DEF" ); // SEND TO CLIENT ABC-DEF
pubnub.publish(args, new Callback() {
public void successCallback(String channel, Object message) {
System.out.println("PUBLISH : " + message);
}
public void errorCallback(String channel, Object message) {
System.out.println("PUBLISH : " + message);
}
});
I'm not into Android world, but isn't it the service you're looking for ? : http://developer.android.com/google/gcm/index.html