arduno control and monitor operation changes

NuwanSameera 9 years ago
parent 0c9b258958
commit 3685a0ef48

@ -190,65 +190,18 @@ public class ArduinoService {
@FormParam("state") String state, @FormParam("state") String state,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
try { LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
DeviceValidator deviceValidator = new DeviceValidator();
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId,
ArduinoConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
return;
}
} catch (DeviceManagementException e) {
log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return;
}
String switchToState = state.toUpperCase();
if (!switchToState.equals(ArduinoConstants.STATE_ON) && !switchToState.equals(ArduinoConstants.STATE_OFF)) {
log.error("The requested state change shoud be either - 'ON' or 'OFF'");
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
return;
}
String protocolString = protocol.toUpperCase();
String callUrlPattern = ArduinoConstants.BULB_CONTEXT + switchToState;
if (log.isDebugEnabled()) { String operation = "BULB:" + state.toUpperCase();
log.debug("Sending request to switch-bulb of device [" + deviceId + "] via " + log.info(operation);
protocolString); if (deviceControlList == null) {
deviceControlList = new LinkedList<>();
deviceControlList.add(operation);
internalControlsQueue.put(deviceId,deviceControlList);
} else {
deviceControlList.add(operation);
} }
try {
/*switch (protocolString) {
case HTTP_PROTOCOL:
String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
if (deviceHTTPEndpoint == null) {
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return;
}
ArduinoServiceUtils.sendCommandViaHTTP(deviceHTTPEndpoint, callUrlPattern, true);
break;
case MQTT_PROTOCOL:
String mqttMessage = ArduinoConstants.BULB_CONTEXT.replace("/", "");
ArduinoServiceUtils.sendCommandViaMQTT(owner, deviceId, mqttMessage, switchToState);
break;
default:
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return;
}*/
String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
if (deviceHTTPEndpoint == null) {
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return;
}
ArduinoServiceUtils.sendCommandViaHTTP(deviceHTTPEndpoint, callUrlPattern, true);
} catch (DeviceManagementException e) {
log.error("Failed to send switch-bulb request to device [" + deviceId + "] via " + protocolString);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return;
}
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
} }
@ -271,40 +224,10 @@ public class ArduinoService {
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
SensorRecord sensorRecord = null; SensorRecord sensorRecord = null;
DeviceValidator deviceValidator = new DeviceValidator();
try { try {
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId,
ArduinoConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
String protocolString = protocol.toUpperCase();
if (log.isDebugEnabled()) {
log.debug(
"Sending request to read raspberrypi-temperature of device [" + deviceId + "] via " +
protocolString);
}
try {
String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
if (deviceHTTPEndpoint == null) {
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
}
String temperatureValue = ArduinoServiceUtils.sendCommandViaHTTP(deviceHTTPEndpoint,
ArduinoConstants
.TEMPERATURE_CONTEXT,
false);
SensorDataManager.getInstance().setSensorRecord(deviceId, ArduinoConstants.SENSOR_TEMPERATURE,
temperatureValue,
Calendar.getInstance().getTimeInMillis());
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
ArduinoConstants.SENSOR_TEMPERATURE); ArduinoConstants.SENSOR_TEMPERATURE);
} catch (DeviceManagementException | DeviceControllerException e) { } catch ( DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} }
@ -323,49 +246,18 @@ public class ArduinoService {
String owner = dataMsg.owner; String owner = dataMsg.owner;
String deviceId = dataMsg.deviceId; String deviceId = dataMsg.deviceId;
String deviceIp = dataMsg.reply; //TODO:: Get IP from request
float pinData = dataMsg.value; float pinData = dataMsg.value;
try { SensorDataManager.getInstance().setSensorRecord(deviceId, ArduinoConstants.SENSOR_TEMPERATURE,
DeviceValidator deviceValidator = new DeviceValidator();
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId,
ArduinoConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
log.warn("Data Received from unregistered Arduino device [" + deviceId + "] for owner [" + owner + "]");
return;
}
String registeredIp = deviceToIpMap.get(deviceId);
if (registeredIp == null) {
log.warn("Unregistered IP: Arduino Pin Data Received from an un-registered IP " + deviceIp +
" for device ID - " + deviceId);
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return;
} else if (!registeredIp.equals(deviceIp)) {
log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId +
" is already registered under some other IP. Re-registration required");
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return;
}
if (log.isDebugEnabled()) {
log.debug("Received Pin Data Value: " + pinData + " degrees C");
}
SensorDataManager.getInstance().setSensorRecord(deviceId, ArduinoConstants.SENSOR_TEMPERATURE,
String.valueOf(pinData), String.valueOf(pinData),
Calendar.getInstance().getTimeInMillis()); Calendar.getInstance().getTimeInMillis());
if (!ArduinoServiceUtils.publishToDAS(dataMsg.owner, dataMsg.deviceId, dataMsg.value)) { if (!ArduinoServiceUtils.publishToDAS(dataMsg.owner, dataMsg.deviceId, dataMsg.value)) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.warn("An error occured whilst trying to publish pin data of Arduino with ID [" + deviceId + log.warn("An error occured whilst trying to publish pin data of Arduino with ID [" + deviceId +
"] of owner [" + owner + "]"); "] of owner [" + owner + "]");
}
} catch (DeviceManagementException e) {
String errorMsg = "Validation attempt for deviceId [" + deviceId + "] of owner [" + owner + "] failed.\n";
log.error(errorMsg + Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase() + "\n" + e.getErrorMessage());
} }
} }
/** /**
@ -397,6 +289,7 @@ public class ArduinoService {
response.setStatus(HttpStatus.SC_NO_CONTENT); response.setStatus(HttpStatus.SC_NO_CONTENT);
} }
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug(result); log.debug(result);
} }

@ -27,20 +27,19 @@
#define ADAFRUIT_CC3000_VBAT 5 #define ADAFRUIT_CC3000_VBAT 5
#define ADAFRUIT_CC3000_CS 10 #define ADAFRUIT_CC3000_CS 10
#define WLAN_SSID "SSID" // cannot be longer than 32 characters! #define WLAN_SSID "ssid" // Your wifi network SSID (cannot be longer than 32 characters!)
#define WLAN_PASS "password" #define WLAN_PASS "password" // Your wifi network password
#define WLAN_SECURITY WLAN_SEC_WPA2 #define WLAN_SECURITY WLAN_SEC_WPA2
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2 // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define IDLE_TIMEOUT_MS 3000 #define IDLE_TIMEOUT_MS 3000
#define DEVICE_OWNER "${DEVICE_OWNER}"
#define DEVICE_ID "${DEVICE_ID}" #define DEVICE_OWNER "${DEVICE_OWNER}"
#define DEVICE_ID "${DEVICE_ID}"
#define DEVICE_TOKEN "${DEVICE_TOKEN}" #define DEVICE_TOKEN "${DEVICE_TOKEN}"
#define REFRESH_DEVICE_TOKEN "${DEVICE_REFRESH_TOKEN}" #define REFRESH_DEVICE_TOKEN "${DEVICE_REFRESH_TOKEN}"
#define SERVICE_PORT 9763
#define SERVICE_EPOINT "/arduino/controller/" #define SERVICE_EPOINT "/arduino/controller/"
#define POLL_INTERVAL 1000 #define POLL_INTERVAL 1000
@ -48,7 +47,14 @@
#define DEBUG true #define DEBUG true
#define CON_DEBUG true #define CON_DEBUG true
byte server[4] = { 192, 168, 1, 101 }; byte server[4] = {192,168,43,168}; //Ip address of iot server
#define SERVICE_PORT 9763 //http port of iot server
byte dns2[] = { 8, 8, 8, 8 }; //Ststic dns of arduino
byte subnet[] = { 255, 255, 255, 0 }; //Ststic subnet of arduino
byte gateway[] = { 192, 168, 43, 1 }; //Ststic gateway of arduino
byte deviceIP[4] = { 192, 168, 43,11 }; //Ststic ip address of arduino
String host, jsonPayLoad, replyMsg; String host, jsonPayLoad, replyMsg;
String responseMsg, subStrn; String responseMsg, subStrn;
double cpuTemperature =0; double cpuTemperature =0;
@ -59,4 +65,3 @@ static unsigned long pollTimestamp = 0;
#endif #endif

@ -31,20 +31,25 @@ uint32_t sserver;
void setup() void setup()
{ {
Serial.begin(9600); Serial.begin(115200);
Serial.println(F("Internal Temperature Sensor")); Serial.println(F("Internal Temperature Sensor"));
pinMode(6, OUTPUT); pinMode(6, OUTPUT);
pinMode(13, OUTPUT);
connectHttp(); connectHttp();
setupResource(); setupResource();
wdt_enable(WDTO_8S); wdt_enable(WDTO_8S);
} }
void loop() void loop()
{ {
wdt_reset();
while( !cc3000.checkConnected() ){ while( !cc3000.checkConnected() ){
connectHttp(); connectHttp();
} }
cpuTemperature=getBoardTemp(); cpuTemperature=getBoardTemp();
@ -60,16 +65,19 @@ void loop()
//Serial.println("PUSHED"); //Serial.println("PUSHED");
wdt_reset();
if(millis() - pollTimestamp > POLL_INTERVAL){ if(millis() - pollTimestamp > POLL_INTERVAL){
while (!client.connected()) { while (!client.connected()) {
setupClient(); setupClient();
} }
Serial.println("Read Controls");
readControls(); readControls();
pollTimestamp = millis(); pollTimestamp = millis();
} }
//Serial.println("LOOPING"); // //Serial.println("LOOPING");
wdt_reset(); wdt_reset();
} }

@ -20,18 +20,9 @@
/********************************************************************************************** /**********************************************************************************************
Use the below variables when required to set a static IP for the WifiSheild Use the below variables when required to set a static IP for the WifiSheild
***********************************************************************************************/ ***********************************************************************************************/
// byte dns2[] = { 8, 8, 8, 8 };
// byte subnet[] = { 255, 255, 255, 0 }; uint32_t ip, ddns, ssubnet, ggateway;
// byte gateway[] = { 10, 100, 9, 254 };
// byte deviceIP[4] = { 10, 100, 9, 9 };
// byte gateway[] = { 192, 168, 1, 1 };
// byte deviceIP[4] = { 192, 168, 1, 219 };
// uint32_t ip, ddns, ssubnet, ggateway;
// byte mac[6] = { 0xC0, 0x4A, 0x00, 0x1A, 0x08, 0xDA }; //mac - c0:4a:00:1a:08:da
// c0:4a:00:1a:03:f8
// b8:27:eb:88:37:7a
String connecting = "connecting.... "; String connecting = "connecting.... ";
void connectHttp() { void connectHttp() {
@ -42,31 +33,19 @@ void connectHttp() {
if(DEBUG) Serial.println(F("Couldn't begin()! Check your wiring?")); if(DEBUG) Serial.println(F("Couldn't begin()! Check your wiring?"));
while(1); while(1);
} }
// if( cc3000.setMacAddress(mac) ) { // Set your own mac and print it to re-check
// uint8_t address[6];
// cc3000.getMacAddress(address);
// if(DEBUG){
// Serial.print(address[0], HEX); Serial.print(":");
// Serial.print(address[1], HEX); Serial.print(":");
// Serial.print(address[2], HEX); Serial.print(":");
// Serial.print(address[3], HEX); Serial.print(":");
// Serial.print(address[4], HEX); Serial.print(":");
// Serial.println(address[5], HEX);
// }
// }
/********************************************************************************************** /**********************************************************************************************
Only required if using static IP for the WifiSheild Only required if using static IP for the WifiSheild
***********************************************************************************************/ ***********************************************************************************************/
// ip = cc3000.IP2U32(deviceIP[0], deviceIP[1], deviceIP[2], deviceIP[3]); ip = cc3000.IP2U32(deviceIP[0], deviceIP[1], deviceIP[2], deviceIP[3]);
// ddns = cc3000.IP2U32(dns2[0], dns2[1], dns2[2], dns2[3]); ddns = cc3000.IP2U32(dns2[0], dns2[1], dns2[2], dns2[3]);
// ssubnet = cc3000.IP2U32(subnet[0], subnet[1], subnet[2], subnet[3]); ssubnet = cc3000.IP2U32(subnet[0], subnet[1], subnet[2], subnet[3]);
// ggateway = cc3000.IP2U32(gateway[0], gateway[1], gateway[2], gateway[3]); ggateway = cc3000.IP2U32(gateway[0], gateway[1], gateway[2], gateway[3]);
// cc3000.setStaticIPAddress(ip, ssubnet, ggateway, ddns); // required for setting static IP cc3000.setStaticIPAddress(ip, ssubnet, ggateway, ddns); // required for setting static IP
/***********************************************************************************************/ /***********************************************************************************************/
sserver = cc3000.IP2U32(server[0], server[1], server[2], server[3]); sserver = cc3000.IP2U32(server[0], server[1], server[2], server[3]);
@ -74,6 +53,8 @@ void connectHttp() {
Serial.print(F("\nAttempting to connect to ")); Serial.print(F("\nAttempting to connect to "));
Serial.println(WLAN_SSID); Serial.println(WLAN_SSID);
} }
cc3000.deleteProfiles();
if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) { if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
if(CON_DEBUG) Serial.println(F("Failed!")); if(CON_DEBUG) Serial.println(F("Failed!"));
@ -85,24 +66,26 @@ void connectHttp() {
if(CON_DEBUG) Serial.println(F("Request DHCP")); if(CON_DEBUG) Serial.println(F("Request DHCP"));
while (!cc3000.checkDHCP()) while (!cc3000.checkDHCP())
{ {
delay(100); // ToDo: Insert a DHCP timeout! delay(100);
} }
/* Display the IP address DNS, Gateway, etc. */ /* Display the IP address DNS, Gateway, etc. */
while (! displayConnectionDetails()) { while (! displayConnectionDetails()) {
delay(1000); delay(1000);
} }
client = cc3000.connectTCP(sserver, SERVICE_PORT); //SERVICE_PORT if (cc3000.checkConnected()) {
if (client.connected()) { Serial.println("client Connected to AP");
if(CON_DEBUG) Serial.println("client Connected to server"); client = cc3000.connectTCP(sserver, SERVICE_PORT);
} else { if (client.connected()) {
if(CON_DEBUG) Serial.println(F("client Connection failed")); if(CON_DEBUG) Serial.println("client Connected to server");
} } else {
if(CON_DEBUG) Serial.println(F("client Connection failed"));
}
} else {
Serial.println(F("client Connection to AP failed"));
}
if(CON_DEBUG) Serial.println(F("-------------------------------------")); if(CON_DEBUG) Serial.println(F("-------------------------------------"));
} }
@ -172,4 +155,4 @@ void setupClient(){
} }
if(CON_DEBUG) Serial.println(F("client Connection failed")); if(CON_DEBUG) Serial.println(F("client Connection failed"));
} }
} }

@ -19,20 +19,30 @@
#include "ArduinoBoardSketch.h" #include "ArduinoBoardSketch.h"
void readControls() { void readControls() {
// String responseMsg; // String responseMsg;
Serial.println("Started..");
client.fastrprint(F("GET ")); client.fastrprint(F("GET "));
client.fastrprint(SERVICE_EPOINT); client.fastrprint(SERVICE_EPOINT);
client.fastrprint(F("readcontrols/")); client.fastrprint(F("readcontrols"));
client.fastrprint(F(" HTTP/1.1"));
client.fastrprint(F("\n"));
client.fastrprint(host.c_str());
client.fastrprint(F("\n"));
client.fastrprint(DEVICE_ID); client.fastrprint(DEVICE_ID);
client.fastrprint(F("?owner=")); client.fastrprint(F("owner: "));
client.fastrprint(DEVICE_OWNER); client.fastrprint(DEVICE_OWNER);
client.fastrprint(F(" HTTP/1.1")); client.fastrprint(F("\n")); client.fastrprint(F("\n"));
client.fastrprint(host.c_str()); client.fastrprint(F("\n")); client.fastrprint(F("deviceId: "));
client.fastrprint(F(DEVICE_ID));
client.fastrprint(F("\n"));
client.fastrprint(F("deviceId: "));
client.fastrprint(F("protocol: HTTP\n"));
client.println(); client.println();
delay(1000);
delay(1000);
Serial.println("Ended..");
while (client.available()) { while (client.available()) {
char response = client.read(); char response = client.read();
responseMsg += response; responseMsg += response;
@ -42,6 +52,7 @@ void readControls() {
int newLine = responseMsg.lastIndexOf("\n"); int newLine = responseMsg.lastIndexOf("\n");
subStrn = responseMsg.substring(index + 1); subStrn = responseMsg.substring(index + 1);
responseMsg = responseMsg.substring(newLine + 1, index); responseMsg = responseMsg.substring(newLine + 1, index);
if(DEBUG) { if(DEBUG) {
Serial.print(responseMsg); Serial.print(responseMsg);
Serial.println(); Serial.println();
@ -50,12 +61,12 @@ void readControls() {
if (subStrn.equals("ON")) { if (subStrn.equals("ON")) {
Serial.println("ITS ON"); Serial.println("ITS ON");
//digitalWrite(13, HIGH); digitalWrite(13, HIGH);
digitalWrite(6, HIGH); digitalWrite(6, HIGH);
} else if (subStrn.equals("OFF")){ } else if (subStrn.equals("OFF")){
Serial.println("ITS OFF"); Serial.println("ITS OFF");
//digitalWrite(13, LOW); digitalWrite(13, LOW);
digitalWrite(6, LOW); digitalWrite(6, LOW);
} }
@ -63,4 +74,3 @@ void readControls() {
} }

@ -25,7 +25,7 @@
***********************************************************************************************/ ***********************************************************************************************/
void pushData(){ void pushData(){
String payLoad = "Data"; String payLoad = "Temp";
payLoad = payLoad + "\",\"value\":\""; payLoad = payLoad + "\",\"value\":\"";
@ -48,7 +48,8 @@ void pushData(){
if(DEBUG) { if(DEBUG) {
Serial.print("POST "); Serial.print("POST ");
Serial.print(SERVICE_EPOINT); Serial.print("pushdata"); Serial.print(SERVICE_EPOINT);
Serial.print("pushdata");
Serial.print(" HTTP/1.1"); Serial.println(); Serial.print(" HTTP/1.1"); Serial.println();
Serial.print(host); Serial.println(); Serial.print(host); Serial.println();
Serial.print("Content-Type: application/json"); Serial.println(); Serial.print("Content-Type: application/json"); Serial.println();
@ -135,4 +136,3 @@ double getBoardTemp(void)
// The returned temperature is in degrees Celcius. // The returned temperature is in degrees Celcius.
return (t); return (t);
} }

Loading…
Cancel
Save