Sending a Message in Change On-line through REST from an Arduino MKR1000

Sending a Message in Change On-line through REST from an Arduino MKR1000 That is half 2 of my MKR1000 article, on this earlier publish I checked out sending a Message through EWS utilizing Primary Authentication.  On this Submit I will take a look at utilizing the brand new Outlook REST API which requires utilizing OAuth authentication to get an Entry Token.

The stipulations for this sketch are the identical as within the different publish with the addition of the ArduinoJson library https://github.com/bblanchon/ArduinoJson which is used to parse the Authentication Outcomes to extract the Entry Token. Additionally the SSL certificates for the login.home windows.web  and outlook.workplace365.com should be uploaded to the gadgets utilizing the wifi101 Firmware updater.

To make use of Token Authentication you want to register an Software in Azure https://msdn.microsoft.com/en-us/workplace/workplace365/howto/add-common-consent-manually with the Mail.Ship permission. The applying must be a Native Shopper app that use the Out of Band Callback urn:ietf:wg:oauth:2.0:oob. It is advisable to authorize it in you tenant (eg construct a small app that may do this which can immediate for authorization). One that’s finished you then must set that ClientId variable within the sketch

String ClientId = “8fe353d6-efa0-4b0f-aafb-ab7cf3a9b307”;

I’ve put a replica of this Sketch up https://github.com/gscales/Arduino-MRK1000/blob/grasp/REST-Workplace365SendSample.ino the code seems like

#embrace <ArduinoJson.h>

#embrace <Base64.h>
#embrace <ArduinoHttpClient.h>

/*
This instance creates a shopper object that connects and transfers
information utilizing all the time SSL.

It's suitable with the strategies usually associated to plain
connections, like shopper.join(host, port).

Written by Arturo Guadalupi
final revision November 2015

*/

#embrace <SPI.h>
#embrace <WiFi101.h>

char ssid[] = "SSOecure"; // your community SSID (identify)
char cross[] = "[email protected]#"; // your community password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your community key Index quantity (wanted just for WEP)
const size_t MAX_CONTENT_SIZE = 5120;

//Workplace365 Credentials
String ExUserName = "[email protected]";
String ExPassword = "passw";
String ClientId = "8fe353d6-efa0-4b0f-aafb-ab7cf3a9b307";
//Message Particulars
String Auth = ExUserName + ":" + ExPassword;
String Topic = "Subject of the Message";
String To = "[email protected]";
String Physique = "Something happening in the Body";
String Access_Token = "";

bool DebugResponse = false;

int cCount = 0;

int standing = WL_IDLE_STATUS;
// in the event you do not wish to use DNS (and scale back your sketch measurement)
// use the numeric IP as a substitute of the identify for the server:

// Initialize the Ethernet shopper library
// with the IP handle and port of the server
// that you just wish to hook up with (port 80 is default for HTTP):
WiFiSSLClient shopper;

void setup() {
//Initialize serial and watch for port to open:
Serial.start(9600);
whereas (!Serial) {
; // watch for serial port to attach. Wanted for native USB port solely
}

// test for the presence of the defend:
if (WiFi.standing() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// do not proceed:
whereas (true);
}

// try to connect with Wifi community:
whereas (standing != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Hook up with WPA/WPA2 community. Change this line if utilizing open or WEP community:
standing = WiFi.start(ssid, cross);

// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
TokenAuth(ClientId,ExUserName,ExPassword);
if(Access_Token.size() > 0){
Serial.println("Send Message");
SendRest(Access_Token,To,Topic,Physique);
Serial.println("Done");
}

}

void TokenAuth(String ClientId,String UserName, String Password)
{
char endOfHeaders[] = "rnrn";
char passwordCA[Password.size()+1];
Password.toCharArray(passwordCA,Password.size()+1);
String content material = "resource=https%3A%2F%2Foutlook.office.com&client_id=" + ClientId + "&grant_type=password&username=" + ExUserName + "&password=" + URLEncode(passwordCA) + "&scope=openid";
Serial.println("nBeginning connection to server...");
if (shopper.connectSSL("login.windows.net", 443)) {
Serial.println("connected to server");
shopper.print("POST ");
shopper.println("https://login.windows.net/Common/oauth2/token HTTP/1.1");
shopper.println("Content-Type: application/x-www-form-urlencoded");
shopper.println("client-request-id: " + ClientId);
shopper.println("return-client-request-id: true");
shopper.println("x-client-CPU: x32");
shopper.println("x-client-OS: Arduino");
shopper.println("Host: login.windows.net");
shopper.print("Content-Length: ");
shopper.println(content material.size());
shopper.println("Expect: 100-continue");
shopper.println("");
shopper.println(content material);
shopper.discover(endOfHeaders);
bool okay = shopper.discover(endOfHeaders);
if (!okay) {
Serial.println("No response or invalid response!");
}
else{
Serial.println("Request Okay");
}
char response[MAX_CONTENT_SIZE];
readAuthReponse(response, sizeof(response));
}
}

void readAuthReponse(char* content material, size_t maxSize) {
size_t size = shopper.readBytes(content material, maxSize);
content material[length] = 0;
Serial.println(content material);
content material[length] = 0;
DynamicJsonBuffer jsonBuffer;
JsonObject&root = jsonBuffer.parseObject(content material);
if (!root.success()) {
Serial.println("JSON parsing failed!");
}
else{
String token = root["access_token"];
Access_Token = token;
}

}


String URLEncode(const char* msg)
{
const char *hex = "0123456789abcdef";
String encodedMsg = "";

whereas (*msg!=''){
if( ('a' <= *msg && *msg <= 'z')
|| ('A' <= *msg && *msg <= 'Z')
|| ('0' <= *msg && *msg <= '9') ) {
encodedMsg += *msg;
} else {
encodedMsg += '%';
encodedMsg += hex[*msg >> 4];
encodedMsg += hex[*msg & 15];
}
msg++;
}
return encodedMsg;
}


void SendRest(String Bearer,String MessageTo, String MessageSubject, String MessageBody)
{
//DebugResponse = true;
char endOfHeaders[] = "rnrn";
String content material = "{";
content material += " "Message": {";
content material += " "Topic": "" + MessageSubject + "",";
content material += " "Physique": {";
content material += " "ContentType": "Textual content",";
content material += " "Content material": "" + MessageBody + """;
content material += " },";
content material += " "ToRecipients": [";
content material += " {";
content material += " "EmailAddress": {";
content material += " "Tackle": "" + MessageTo + """;
content material += " }";
content material += " }";
content material += " ]";
content material += " },";
content material += " "SaveToSentItems": "false"";
content material += " }";
Serial.println("nBeginning connection to server...");
// in the event you get a connection, report again through serial:
if (shopper.connectSSL("outlook.office365.com", 443)) {
Serial.println("connected to server");
shopper.print("POST ");
shopper.print("https://outlook.office365.com/api/v2.0/me/sendmail");
shopper.println(" HTTP/1.1");
shopper.print("Host: ");
shopper.println("outlook.office365.com");
shopper.print("Authorization: Bearer ");
shopper.println(Bearer);
shopper.println("Connection: close");
shopper.print("Content-Type: ");
shopper.println("application/json");
shopper.println("User-Agent: mrk1000Sender");
shopper.print("Content-Length: ");
shopper.println(content material.size());
shopper.println();
shopper.println(content material);
char okayString[] = "HTTP/1.1 202 Accepted";
bool okay = shopper.discover(okayString);
if (!okay) {
Serial.println("Message Sent");
}
else{
Serial.println("Request Failed");
}
}

}

void loop() {
// if there are incoming bytes out there
// from the server, learn them and print them:
if(DebugResponse){
whereas (shopper.out there()) {
char c = shopper.learn();
Serial.print(c);
}
}

// if the server's disconnected, cease the shopper:
if (!shopper.linked()) {
Serial.println();
Serial.println("disconnecting from server.");
shopper.cease();
// do nothing forevermore:
whereas (true);
}
}


void printWifiStatus() {
// print the SSID of the community you are hooked up to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());

// print your WiFi defend's IP handle:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);

// print the acquired sign energy:
lengthy rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
Tags:

Related Posts

Leave a Reply