LAMPIRAN 1
KODE PROGRAM KONTROLER
Fugue.ino
/ * *
* Fugue – Sebuah pr ogr am Ar dui no unt uk Home Aut omat i on. *
* @pac k age Nugr aha
* @Aut hor Wahy u Nugr aha <nugr aha. c . wahy u@gmai l . c om> * /
#i nc l ude " Fugue. h"
names pac e Mai n {
us i ng Nugr aha: : Foundat i on: : Bas eCont r ol l er ;
c l as s Cont r ol l er : publ i c v i r t ual Bas eCont r ol l er {
publ i c:
v oi d s et up( ) {
Debug: : i s DebugMode = t r ue;
i f( ! env : : wi f i : : obt ai nI pAddr es s Aut omat i c al l y ) {
Wi Fi .c onf i g( env : : wi f i : : i p, env : : wi f i : : gat eway , env : : wi f i : : s ubnet , env : : wi f i : : dns 1, env : : wi f i : : dns 2) ;
}
boar d- >i ni t i al i z e( ) ; boar d- >aut omat e( ) ; }
v oi d l oop( ) {
Sc hedul er: : handl eEv ent s ( ) ; }
} ;
}
#i nc l ude " boot s t r ap/ boot s t r ap. hpp"
App/Boards/WemosD1.hpp
namespace App { namespace Boards {
usingnamespace App::Devices;
using Nugraha::Foundation::Board;
using App::Gateways::WebServer::Server;
classWemosD1 : publicvirtual Board {
protected:
void gateways() {
// this->attachGateway(new Server());
this->attachGateway(new PersistentHttp(std::map<String, String>({ { "host" , env::httpClient::host },
{ "mode" , env::httpClient::mode },
{ "publishKey" , env::httpClient::publishKey }, { "subscribeKey" , env::httpClient::subscribeKey }, { "signature" , env::httpClient::signature }, { "channelName" , env::httpClient::channelName }, { "callback" , env::httpClient::callback } })));
}
void devices() {
this->attachDevice(new Lampu(D2, NULL));
this->attachDevice(new Lampu(D3, NULL));
this->attachDevice(new Lampu(D4, NULL));
this->attachDevice(new Lampu(D5, NULL));
this->attachDevice(new AirConditioner(D6, NULL));
this->attachDevice(new LED(BUILTIN_LED, NULL)); }
void sensors() {
} };
}}
app/Devices/AirConditioner.hpp
namespace App { namespace Devices {
using Nugraha::Sensors::Sensor;
using Nugraha::Devices::Device;
using Nugraha::Devices::Drivers::AirConditionerDriver;
classAirConditioner : publicvirtual Device {
public:
AirConditioner(int pin, Sensor* sensor=NULL) : Device(pin, sensor) {}
void initialize() {
pinMode(this->pin, OUTPUT);
setDriver(new AirConditionerDriver()); }
{
} };
}}
app/Devices/Lampu.hpp
namespace App { namespace Devices {
using Nugraha::Sensors::Sensor;
using Nugraha::Devices::Device;
classLampu : publicvirtual Device {
public:
Lampu(int pin, Sensor* sensor=NULL) : Device(pin, sensor) {}
void initialize() {
pinMode(this->pin, OUTPUT); }
void behavior() {
} };
}}
app/Gateways/HttpClients/NonPersistentHttp.hpp
namespace App { namespace Gateways { namespace HttpClients { using Nugraha::Gateways::Esp8266::WifiHttpClient;
classNonPersistentHttp : publicvirtual WifiHttpClient {
public:
NonPersistentHttp(std::map<String, String> setting):WifiHttpClient(setting) {}
void service() {
Debug::println("Memulai service koneksi HTTP Non-persistent...");
interval = 0;
http.setReuse(false);
Scheduler::every(interval, [=]() { updateMessage();
httpGet(generateUri(), [=]() {
board->executeUserCommand(response); });
}}}
app/Gateways/HttpClients/PersistentHttp.hpp
namespace App { namespace Gateways { namespace HttpClients { using Nugraha::Gateways::Esp8266::WifiHttpClient;
classPersistentHttp : publicvirtual WifiHttpClient {
public:
PersistentHttp(std::map<String, String> setting) : WifiHttpClient(setting) {}
void service() {
Debug::println("Memulai service koneksi HTTP Persistent...");
interval = 0;
http.setReuse(true);
Scheduler::every(interval, [=]() { updateMessage();
httpGet(generateUri(), [=]() {
board->executeUserCommand(response); });
}); } };
}}}
config/env.hpp
namespace env {
namespace wifi {
String ssid = "Fugue2";
String password = "fugue123"; bool obtainIpAddressAutomatically = false; IPAddress ip(192, 168, 137, 69); IPAddress subnet(255, 255, 255, 0); IPAddress gateway(192, 168, 137, 1); IPAddress dns1(8, 8, 8, 8);
IPAddress dns2(8, 8, 4, 4); }
namespace httpClient {
String host = "www.wahyunugraha.com"; String mode = "publish";
String publishKey = "pub-w-3e5de365-5d57-48c7-a317-366ef2846eb4"; String subscribeKey = "sub-n-cca59b64-d972-11e5-bdd5-02ee2ddab7fe"; String signature = "0";
String channelName = "rumah1"; String callback = "0";
namespace server {
ESP8266WebServer* server = new ESP8266WebServer(80); }
}
vendor/nugraha/tugasAkhirWahyu/src/Nugraha/Devices/Drivers/AirConditionerDriver.hpp
namespace Nugraha { namespace Devices { namespace Drivers { using Nugraha::Support::Facades::Scheduler::Scheduler;
classAirConditionerDriver: publicvirtual Driver {
protected:
public:
bool turnOn(int pin) {
digitalWrite(pin, HIGH); Scheduler::after(50, [=]() { digitalWrite(pin, LOW); });
returntrue; }
bool turnOff(int pin) {
digitalWrite(pin, HIGH); Scheduler::after(50, [=]() { digitalWrite(pin, LOW); });
returntrue; } };
}}}
vendor/nugraha/tugasAkhirWahyu/src/Nugraha/Devices/Drivers/SinkModeDriver.hpp
namespace Nugraha { namespace Devices { namespace Drivers {
classSinkModeDriver : publicvirtual Driver {
protected:
public:
bool turnOn(int pin) {
digitalWrite(pin, LOW);
returntrue; }
bool turnOff(int pin) {
digitalWrite(pin, HIGH);
}}}
vendor/nugraha/tugasAkhirWahyu/src/Nugraha/Devices/Device.hpp
namespace Nugraha { namespace Devices { using Nugraha::Traits::HasId;
classDevice : publicvirtual DeviceContract, public HasLogger, public HasId {
protected: int pin = -1; bool isOn = false;
SensorContract* sensor; DriverContract* driver; unsignedlong previousMillis = 0; static DriverContract* defaultDriver;
public:
Device(int pin, SensorContract* sensor) {
this->pin = pin; this->sensor = sensor;
this->driver = Device::defaultDriver; }
virtual ~Device() {}
void toggle()
if(driver->turnOn(this->pin)) { this->isOn = true;
logger->addNotification(1, String(this->pin));
if(driver->turnOff(this->pin)) { this->isOn = false;
logger->addNotification(0, String(this->pin)); }
}
int getPin() {
returnthis->pin; }
void setSensor(SensorContract* sensor) {
this->sensor = sensor; }
void setDriver(DriverContract* driver) {
this->driver = driver; }
int getId() override {HasId::getId();}
void setLogger(LoggerContract* logger) override {HasLogger::setLogger(logger);}
LoggerContract* getLogger() override {HasLogger::getLogger();} };
}}
vendor/nugraha/tugasAkhirWahyu/src/Nugraha/Foundation/Application.hpp
namespace Nugraha { namespace Foundation {
using Nugraha::Contracts::Foundation::BoardContract;
classApplication
{
public:
BaseController* controller; int serialBaudRate;
bool beginSerial;
Application(BaseController* controller, BoardContract* board, int serialBaudRate, bool beginSerial)
{
this->controller = controller;
this->controller->board = board;
this->serialBaudRate = serialBaudRate;
this->beginSerial = beginSerial; }
virtual ~Application() {}
virtualvoid setup() {
this->controller->setup(); }
virtualvoid loop() {
};
}}
vendor/nugraha/tugasAkhirWahyu/src/Nugraha/Foundation/BaseController.hpp
namespace Nugraha { namespace Foundation {
using Nugraha::Contracts::Foundation::BoardContract;
classBaseController
{
public:
BoardContract* board;
virtual ~BaseController() {}
virtualvoid setup()=0;
virtualvoid loop()=0; };
}}
vendor/nugraha/tugasAkhirWahyu/src/Nugraha/Foundation/Board.hpp
namespace Nugraha { namespace Foundation {
using Nugraha::Traits::HasLogger;
using Nugraha::Collections::Vector;
using Nugraha::Contracts::Devices::DeviceContract;
using Nugraha::Contracts::Sensors::SensorContract;
using Nugraha::Contracts::Gateways::GatewayContract;
using Nugraha::Contracts::Foundation::BoardContract;
using Nugraha::Contracts::Foundation::LoggerContract;
using Nugraha::Contracts::Collections::CollectionContract;
classBoard : publicvirtual BoardContract, public HasLogger {
protected:
CollectionContract<DeviceContract*>* devicesCollection; CollectionContract<SensorContract*>* sensorsCollection; CollectionContract<GatewayContract*>* gatewaysCollection; DeviceContract* Default = NULL;
voidinitializeAll() {
/** Inisialisasi setiap Gateway. */
for(int i=0; i<gatewaysCollection->count(); i++) {
if(gatewaysCollection->getMemberAt(i) != NULL) {
gatewaysCollection->getMemberAt(i)->initialize(); }
}
/** Inisialisasi setiap Device. */
for(int i=0; i<devicesCollection->count(); i++) {
if(devicesCollection->getMemberAt(i) != NULL) {
} }
public: Board() {
devicesCollection = new Vector<DeviceContract*>(); sensorsCollection = new Vector<SensorContract*>(); gatewaysCollection = new Vector<GatewayContract*>(); setLogger(new Logger());
}
void initialize() {
sensors(); devices(); gateways(); initializeAll(); }
void automate() {
/** Jalankan behavior setiap Device. */
for(int i=0; i<devicesCollection->count(); i++) {
if(devicesCollection->getMemberAt(i) != NULL) {
devicesCollection->getMemberAt(i)->behavior();
devicesCollection->getMemberAt(i)->setLogger(logger); }
}
/** Jalankan service setiap Gateway. */
for(int i=0; i<gatewaysCollection->count(); i++) {
if(gatewaysCollection->getMemberAt(i) != NULL) {
gatewaysCollection->getMemberAt(i)->service();
gatewaysCollection->getMemberAt(i)->setLogger(logger); gatewaysCollection->getMemberAt(i)->setBoard(this); }
} }
void attachDevice(DeviceContract* device) {
devicesCollection->add(device); }
void attachSensor(SensorContract* sensor) {
sensorsCollection->add(sensor); }
void attachGateway(GatewayContract* gateway) {
gatewaysCollection->add(gateway); }
void executeUserCommand(String userCommands) {
DeviceContract* device;
JsonObject& root = jsonBuffer.parseObject(userCommands);
if (!root.success()) {
Serial.println("parseObject() failed");
return; }
for(int i=0; i<root["commands"].size(); i++) { int pin = root["commands"][i]["pin"];
String action = root["commands"][i]["action"];
if(action=="turnOn") {
if((device=getDeviceByPin(pin)) != NULL) { device->turnOn(); }
} elseif(action=="turnOff") {
if((device=getDeviceByPin(pin)) != NULL) { device->turnOff(); }
} elseif(action=="toggle") {
if((device=getDeviceByPin(pin)) != NULL) { device->toggle(); }
} } }
DeviceContract* getDeviceByPin(int pin) {
DeviceContract* device;
for(int i=0; i<devicesCollection->count(); i++) {
device = devicesCollection->getMemberAt(i);
if(device != NULL) {
if(device->getPin() == pin) {
return device; } } }
returnNULL; }
~Board() {
delete gatewaysCollection;
delete devicesCollection;
delete sensorsCollection;
delete logger; }
};
}}
vendor/nugraha/tugasAkhirWahyu/src/Nugraha/Foundation/Logger.hpp
namespace Nugraha { namespace Foundation {
classLogger : public LoggerContract {
protected:
DynamicJsonBuffer* jsonBuffer = new DynamicJsonBuffer(); JsonObject* root = &jsonBuffer->createObject();
JsonArray* notifications = &root->createNestedArray("notifications"); JsonArray* measurements = &root->createNestedArray("measurements"); JsonArray* connectionInfos =
&root->createNestedArray("connectionInfos");
bool sendBoardInfo = true;
voidclean() {
delete jsonBuffer;
jsonBuffer = NULL;
notifications = &root->createNestedArray("notifications"); measurements = &root->createNestedArray("measurements");
connectionInfos = &root->createNestedArray("connectionInfos"); }
voidaddBoardInfoToRecord() {
JsonObject& boardInfo = root->createNestedObject("boardInfo"); boardInfo["chipId"] = ESP.getChipId();
boardInfo["freeSketchSpace"] = ESP.getFreeSketchSpace(); }
public:
void addNotification(int code, String message) {
notification["state"] = state; }
void addConnectionInfo(String parameter, String value) {
if(jsonBuffer == NULL)
reInitializeJsonBuffer();
JsonObject& connectionInfo = connectionInfos->createNestedObject(); connectionInfo["parameter"] = parameter;
connectionInfo["value"] = value; }
void addSensorMeasurement(String sensorName, String measurementValue) {
if(jsonBuffer == NULL)
reInitializeJsonBuffer();
JsonObject& measurement = measurements->createNestedObject(); measurement["sensor"] = sensorName;
measurement["value"] = measurementValue; }
String getLogMessage() {
if(jsonBuffer != NULL) {
if(sendBoardInfo) {
addBoardInfoToRecord(); }
String logMessages;
root->printTo(logMessages); clean();
reInitializeJsonBuffer();
return logMessages;
} else {
return"{\"records\":[]}"; }
}
void printToSerial() {
if(jsonBuffer != NULL) {
if(sendBoardInfo) {
addBoardInfoToRecord(); }
root->prettyPrintTo(Serial); }
else
Serial.println("NULL"); }
};
}}
namespace Nugraha { namespace Gateways { namespace Esp8266 {
using Nugraha::Traits::HasId;
using Nugraha::Traits::HasLogger;
using Nugraha::Contracts::Gateways::GatewayContract;
using Nugraha::Contracts::Foundation::BoardContract;
using Nugraha::Contracts::Foundation::LoggerContract;
classWifiHttpClient : publicvirtual GatewayContract, public HasLogger,
public HasId {
protected:
ESP8266WiFiMulti WiFiMulti; HTTPClient http;
BoardContract* board;
String ssid = env::wifi::ssid; String password = env::wifi::password; unsignedlong interval = 1000;
String host; String mode;
String publishKey; String subscribeKey; String signature; String channelName; String callback;
String message = "{\"text\":\"hello\"}"; String response;
public:
WifiHttpClient(std::map<String, String> setting) {
this->host = setting["host"];
this->mode = setting["mode"];
this->publishKey = setting["publishKey"];
this->subscribeKey = setting["subscribeKey"];
this->signature = setting["signature"];
this->channelName = setting["channelName"];
this->callback = setting["callback"]; }
virtual ~WifiHttpClient() {}
void initialize() {
Serial.println(); Serial.println(); Serial.println();
for(uint8_t t = 4; t >0; t--) {
Serial.printf("[SETUP] WAIT %d...\n", t); Serial.flush();
delay(1000); }
WiFiMulti.addAP("Fugue2", "fugue123"); }
{
if(message != "") {
String uri = "http://" + host + "/" + mode + "/" + publishKey + "/" + subscribeKey + "/" + signature + "/" + channelName + "/" + callback + "/" + message;
Serial.println(uri);
return uri; } }
template<typename Callback>
void httpGet(String uri, Callback callback) {
// wait for WiFi connection
if((WiFiMulti.run() == WL_CONNECTED)) { unsignedlong tempMillis = millis(); http.begin(uri);
int httpCode = http.GET();
if(httpCode >0) {
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if(httpCode == HTTP_CODE_OK) { // Hitung delay.
addDelayToRecord(String(millis() - tempMillis)); // Ekstrak pesan dan panggil fungsi callback.
response = http.getString(); callback();
} else {
addDelayToRecord(String(-1)); }
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end(); }
}
int getId() override {HasId::getId();}
void updateMessage() {
this->message = getLogger()->getLogMessage(); }
void setLogger(LoggerContract* logger) override
{
HasLogger::setLogger(logger); addDelayToRecord(String(0)); }
LoggerContract* getLogger() {
return logger;
void setBoard(BoardContract* board) {
this->board = board; }
void addDelayToRecord(String value) {
getLogger()->addConnectionInfo("delay", value); }
};
}}}
vendor/nugraha/tugasAkhirWahyu/src/Nugraha/Sensors/Sensor.hpp
namespace Nugraha { namespace Sensors {
using Nugraha::Traits::HasId;
using Nugraha::Traits::HasLogger;
using Nugraha::Sensors::Drivers::Driver;
using Nugraha::Sensors::Drivers::GenericDriver;
using Nugraha::Contracts::Sensors::SensorContract;
using Nugraha::Contracts::Foundation::LoggerContract;
classSensor : publicvirtual SensorContract, public HasLogger, public HasId {
protected:
Driver* driver;
public: int id; int pin;
constchar* name;
virtual ~Sensor() {}
Sensor(int pin, constchar* name) {
this->pin = pin;
this->name = name;
this->driver = new GenericDriver(); }
int getId() override {HasId::getId();}
void setLogger(LoggerContract* logger) override
{HasLogger::setLogger(logger);}
LoggerContract* getLogger() override {HasLogger::getLogger();} };
}}
namespace Nugraha { namespace Support { namespace Facades { namespace
Scheduler {
using Nugraha::Contracts::Support::Facades::Scheduler::EventContract;
using Nugraha::Traits::HasId;
classBaseEvent : publicvirtual EventContract, publicvirtual HasId {
protected:
unsignedlong interval;
unsignedlong previousMillis; int repeatCount = -1;
public:
BaseEvent(unsignedlong interval, int repeatCount) {
this->previousMillis = millis();
this->interval = interval;
this->repeatCount = repeatCount; }
virtual ~BaseEvent()
{
}
int executionCount = 0; voidupdate(unsignedlong now) {
if(now - previousMillis >= interval && (repeatCount == -1 || repeatCount >0)) {
previousMillis = now;
Serial.printf("[%d] ", this->id); executeCallback();
if(repeatCount != -1) {
repeatCount--; }
} }
intgetRepeatCount() {
return repeatCount;
}
intgetId() override
{
HasId::getId(); }
};
}}}}
vendor/nugraha/tugasAkhirWahyu/src/Nugraha/Support/Facades/Scheduler/Scheduler.hpp
namespace Nugraha { namespace Support { namespace Facades { namespace
Scheduler {
using Nugraha::Collections::Collection;
classScheduler {
protected:
static CollectionContract<BaseEvent*>* eventCollection;
staticbool init;
public:
staticvoid handleEvents() {
if(init) {
after(1, [=](){Serial.println();}); init = false;
}
for(auto event = eventCollection->getMembers().begin(); event != eventCollection->getMembers().end();) {
(*event)->update(millis());
if((*event)->getRepeatCount() == 0) {
delete *event;
*event = NULL;
event = eventCollection->getMembers().erase(event); } else {
++event; }
} }
template<typename Callback>
staticvoid every(unsignedlong interval, Callback callback, int repeatCount = -1)
{
eventCollection->add(new StaticEvent<Callback>(interval, callback, repeatCount));
}
template<typename Callback, typename ObjectType>
staticvoid every(unsignedlong interval, ObjectType object, Callback
callback, int repeatCount = -1) {
eventCollection->add(new Event<Callback, ObjectType>(interval, callback, object, repeatCount));
}
template<typename Callback>
staticvoid after(unsignedlong afterMillis, Callback callback)
{
every(afterMillis, callback, 1); }
static BaseEvent* getEventAt(int index) {
return eventCollection->getMemberAt(index); }
};
CollectionContract<BaseEvent*>* Scheduler::eventCollection = new
}}}}
vendor/nugraha/tugasAkhirWahyu/src/Nugraha/Support/Facades/Scheduler/StaticEvent.hp
p
names pac e Nugr aha { names pac e Suppor t { names pac e Fac ades { names pac e Sc hed-ul er {
t empl at e<c l as s Cal l bac k>
c l as s St at i c Ev ent : publ i c v i r t ual Bas eEv ent {
pr ot ec t ed:
Cal l bac k c al l bac k ;
publ i c:
St at i c Ev ent (uns i gned l ong i nt er v al , Cal l bac k c al l bac k , i nt r epeat Count ) : Bas eEv ent ( i nt er v al , r epeat Count ) , c al l bac k ( c al l bac k )
{ }
v oi d ex ec ut eCal l bac k ( ) {
t hi s- >c al l bac k ( ) ; }
} ;
LAMPIRAN 2
KODE PROGRAM APLIKASI WEB
App/Http/routes.php
<?php
Rout e: :get(' / ' , ' HomeCont r ol l er @i ndex ' ) ; Rout e: :aut h( ) ;
Rout e: :get(' publ i s h/ { publ i s hKey } / { s ubs c r i beKey } / { s i gnat ur e} / { c hannel Name} / { c al l bac k } / { mes s age} ' , ' Publ i s hCont r ol l er @handl e' ) ;
Rout e: :get(' manage/ das hboar d' , ' Das hboar dCont r ol l er @i ndex ' ) ;
Rout e: :get(' manage/ das hboar d/ c ons ol e' , ' Cons ol eCont r ol l er @i ndex ' ) ; Rout e: :get(' not i f i c at i ons ' , ' Not i f i c at i ons Cont r ol l er @i ndex ' ) ; Rout e: :get(' not i f i c at i ons / { not i f i c at i ons } / s een' ,
' Not i f i c at i ons Cont r ol l er @s een' ) ;
Rout e: :get(' meas ur ement s ' , ' Meas ur ement s Cont r ol l er @i ndex ' ) ; Rout e: :get(' meas ur ement s / { meas ur ement s } / s een' ,
' Meas ur ement s Cont r ol l er @s een' ) ;
Rout e: :get(' c onnec t i oni nf os ' , ' Connec t i onI nf os Cont r ol l er @i ndex ' ) ; Rout e: :get(' c onnec t i oni nf os / { c onnec t i oni nf os } / s een' ,
' Connec t i onI nf os Cont r ol l er @s een' ) ;
Rout e: :get(' c ommands / 1/ { pi n} ' , ' Commands Cont r ol l er @t ur nOn' ) ; Rout e: :get(' c ommands / 0/ { pi n} ' , ' Commands Cont r ol l er @t ur nOf f ' ) ;
App/Http/Controllers/CommandsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Command;
use App\Http\Requests;
use Illuminate\Http\JsonResponse;
use Carbon\Carbon;
use App\Traits\ArduinoBoard;
classCommandsControllerextends Controller
{
use ArduinoBoard;
functionturnOn($pin) {
$command = new Command();
$command->pin = $this->getPinValue($pin); $command->action = 'turnOn';
functionturnOff($pin) {
$command = new Command();
$command->pin = $this->getPinValue($pin); $command->action = 'turnOff';
$command->save(); }
}
App/Http/Controllers/ConnectionInfosController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\ConnectionInfo;
use Illuminate\Http\JsonResponse;
classConnectionInfosControllerextends Controller
{
functionindex() {
$connectionInfos = ConnectionInfo::where('seen', false)->get()-> toArray();
return (new JsonResponse(array( "connectionInfos" =>$connectionInfos )));
}
functionseen(ConnectionInfo $connectionInfo) {
$connectionInfo->seen = true; $connectionInfo->save(); }
}
App/Http/Controllers/ConsoleController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Command;
use App\Measurement;
use App\Notification;
use Illuminate\Http\JsonResponse;
{
functionindex() {
return view('dashboard.console.index');
}
}
App/Http/Controllers/DashboardController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
classDashboardControllerextends Controller
{
publicfunction__construct()
{
$this->middleware('auth'); }
publicfunctionindex() {
return view('dashboard.index'); }
}
App/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use App\TugasAkhirWahyu\TugasAkhirWahyu;
classHomeControllerextends Controller {
publicfunction__construct()
{
}
publicfunctionindex() {
} }
App/Http/Controllers/MeasurementsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request; use App\Http\Requests; use App\Measurement;
use Illuminate\Http\JsonResponse;
classMeasurementsControllerextends Controller {
functionindex() {
$notifications = Measurement::where('seen', false)->get()->toArray();
return (new JsonResponse(array( "measurements" =>$notifications )));
}
functionseen(Measurement $measurement) {
$measurement->seen = true; $measurement->save(); }
}
App/Http/Controllers/NotificationsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request; use App\Http\Requests; use App\Notification;
use Illuminate\Http\JsonResponse;
classNotificationsControllerextends Controller {
functionindex() {
$notifications = Notification::where('seen', false)->get()->toArray();
return (new JsonResponse(array( "notifications" =>$notifications )));
}
functionseen(Notification $notification) {
$notification->seen = true; $notification->save(); }
App/Http/Controllers/PublishController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Carbon\Carbon;
use App\Http\Requests;
use App\Command;
use App\Notification;
use App\Device;
use App\Measurement;
use App\ConnectionInfo;
classPublishControllerextends Controller {
functionhandle($publishKey, $subscribeKey, $signature, $channelName, $callback, $message)
{
if($publishKey != "pub-w-3e5de365-5d57-48c7-a317-366ef2846eb4" || $subscribeKey != "sub-n-cca59b64-d972-11e5-bdd5-02ee2ddab7fe") {
return []; }
$this->saveMessages($message);
return$this->sendResponse(); }
functionsaveMessages($message) {
$data = json_decode($message);
$myNotification;
foreach ($data->notificationsas$notification) { $myNotification = new Notification();
$myNotification->pin = $notification->pin; $myNotification->state = $notification->state; $myNotification->seen = false;
$myNotification->save();
$device = Device::where('pin', $myNotification->pin)->get()-> first();
if(isset($device->state)){
if($notification->state == 'on') { $device->state = true;
} elseif($notification->state == 'off') { $device->state = false;
} $device->save(); } }
$myMeasurements;
foreach ($data->measurementsas$measurement) { $myMeasurements = new Measurement();
$myMeasurements->value = $measurement->value; $myMeasurements->seen = false;
$myMeasurements->save(); }
$myConnectionInfos;
foreach ($data->connectionInfosas$connectionInfo) { $myConnectionInfos = new ConnectionInfo();
$myConnectionInfos->parameter = $connectionInfo->parameter; $myConnectionInfos->value = $connectionInfo->value;
$myConnectionInfos->seen = false; $myConnectionInfos->save();
} }
functionsendResponse() {
$commands = Command::where('sent', false)->get();
foreach ($commandsas$command) { $command->sent = true;
$command->sent_at = Carbon::now(); $command->save();
}
return (new JsonResponse(array("commands" =>$commands-> toArray())));
} }
Resources/views/dashboard/index.blade.php
@extends('dashboard.layouts.master')
@section('content')
<div class="row x_title"> <div class="col-md-6">
<h3>Rumah <small>saya</small></h3> </div>
<div class="col-md-6">
</div> </div>
<div class="col-md-12 col-sm-12 col-xs-12"> <table class="table table-inverse">
<thead> <tr>
<th>#</th> <th>Nama</th> <th>Pin</th> <th>Action</th> </tr>
<tr>
<th scope="row">1</th> <td>A/C</td>
<td>D6</td> <td>
<button id="turnOn1" type="button" class="btn btn-primary">On</button> <button id="turnOff1" type="button" class="btn btn-warning">Off</button> </td>
</tr> <tr>
<th scope="row">2</th> <td>Lampu 1</td>
<td>D2</td> <td>
<button id="turnOn2" type="button" class="btn btn-primary">On</button> <button id="turnOff2" type="button" class="btn btn-warning">Off</button> </td>
</tr> <tr>
<th scope="row">3</th> <td>Lampu 2</td>
<td>D3</td> <td>
<button id="turnOn3" type="button" class="btn btn-primary">On</button> <button id="turnOff3" type="button" class="btn btn-warning">Off</button> </td>
</tr> <tr>
<th scope="row">4</th> <td>Lampu 3</td>
<td>D4</td> <td>
<button id="turnOn4" type="button" class="btn btn-primary">On</button> <button id="turnOff4" type="button" class="btn btn-warning">Off</button> </td>
</tr> <tr>
<th scope="row">5</th> <td>Lampu 4</td>
<td>D5</td> <td>
<button id="turnOn5" type="button" class="btn btn-primary">On</button> <button id="turnOff5" type="button" class="btn btn-warning">Off</button> </td>
</tr> <tr>
<th scope="row">6</th> <td>Test Led</td> <td>BUILTIN_LED</td> <td>
<button id="turnOn6" type="button" class="btn btn-primary">On</button> <button id="turnOff6" type="button" class="btn btn-warning">Off</button> </td>
// A/C
$('#turnOn1').click(function() {
$.ajax({url: "/commands/1/d6", success: function(result) {alert("Perintah terkirim!");}});
});
$('#turnOff1').click(function() {
$.ajax({url: "/commands/0/d6", success: function(result) {alert("Perintah terkirim!");}});
});
// Lampu 1
$('#turnOn2').click(function() {
$.ajax({url: "/commands/1/d2", success: function(result) {alert("Perintah terkirim!");}});
});
$('#turnOff2').click(function() {
$.ajax({url: "/commands/0/d2", success: function(result) {alert("Perintah terkirim!");}});
});
// Lampu 2
$('#turnOn3').click(function() {
$.ajax({url: "/commands/1/d3", success: function(result) {alert("Perintah terkirim!");}});
});
$('#turnOff3').click(function() {
$.ajax({url: "/commands/0/d3", success: function(result) {alert("Perintah terkirim!");}});
}); // Lampu 3
$('#turnOn4').click(function() {
$.ajax({url: "/commands/1/d4", success: function(result) {alert("Perintah terkirim!");}});
});
$('#turnOff4').click(function() {
$.ajax({url: "/commands/0/d4", success: function(result) {alert("Perintah terkirim!");}});
});
// Lampu 4
$('#turnOn5').click(function() {
$.ajax({url: "/commands/1/d5", success: function(result) {alert("Perintah terkirim!");}});
});
$('#turnOff5').click(function() {
$.ajax({url: "/commands/0/d5", success: function(result) {alert("Perintah terkirim!");}});
});
// Test Led
$('#turnOn6').click(function() {
$.ajax({url: "/commands/1/builtin_led", success: function(result) {alert("Perintah terkirim!");}});
});
$('#turnOff6').click(function() {
$.ajax({url: "/commands/0/builtin_led", success: function(result) {alert("Perintah terkirim!");}});
</script> @endsection
Resources/views/dashboard/console/index.blade.php
@extends('dashboard.layouts.master')
@section('content')
<div class="row x_title"> <div class="col-md-6">
<h3>Debug <small>Console</small></h3> </div>
<div class="col-md-6">
</div> </div>
<div class="col-md-12 col-sm-12 col-xs-12"> <div id="ayam" class="col-md-6">
</div>
<div id="console" class="col-md-6">
<textarea class="col-md-12" id="myConsoleArea" cols="100" rows="9000" style="background:#000; foreground:#fff; height: 700px;
font-size:16px"></textarea> </div>
</div> <script>
var message = "";
functiongetData() {
$.ajax({url: "/notifications", success: function(result) { result.notifications.forEach(function(notification) {
message += '>> ['+ notification.created_at +'] perangkat pada pin ' + notification.pin + ' telah di-' + notification.state + '-kan\n'; $('#myConsoleArea').html(message);
$.ajax({url: "/notifications/"+notification.id+"/seen", success:
function(result) {}});
});; }});
$.ajax({url: "/measurements", success: function(result) { result.measurements.forEach(function(measurement) {
message += '>> ['+ measurement.created_at +'] pembacaan sensor ' + measurement.sensor + ' adalah: ' + measurement.value + '\n';
$('#myConsoleArea').html(message);
$.ajax({url: "/measurements/"+measurement.id+"/seen", success:
function(result) {}});
});; }});
setTimeout(getData, 3000); }
$(document).ready(function () { getData();
});
</script>
Resources/views/dashboard/layouts/master.blade.php
<!DOCTYPE html> <html lang="en">
<head>
@include('dashboard.layouts.master.header') @yield('header')
</head>
<body class="nav-md">
<div class="container body"> <div class="main_container"> <div class="col-md-3 left_col"> <div class="left_col scroll-view">
<div class="navbar nav_title" style="border: 0;"> <a href="dashboard" class="site_title"><i class="fa fa-paw"></i><span>Dashboard</span></a>
</div>
<div class="clearfix"></div>
<!-- menu profile quick info --> <div class="profile">
@include('dashboard.layouts.master.profileQuickInfo')
</div>
<!-- /menu profile quick info -->
<br />
<!-- sidebar menu -->
<div id="sidebar-menu" class="main_menu_side hidden-print main_menu"> <div class="menu_section">
@include('dashboard.layouts.master.sideBarMenu')
</div> </div>
<!-- /sidebar menu -->
<!-- /menu footer buttons -->
<div class="sidebar-footer hidden-small">
@include('dashboard.layouts.master.menuFooterButtons')
</div>
<div class="clearfix"></div> <!-- /menu footer buttons --> </div>
<!-- top navigation --> <div class="top_nav">
<div class="nav_menu">
<nav class="" role="navigation"> <div class="nav toggle">
<a id="menu_toggle"><i class="fa fa-bars"></i></a> </div>
@include('dashboard.layouts.master.topNavigation') </nav>
</div>
</div>
<!-- /top navigation -->
<!-- page content -->
<div class="right_col" role="main">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12"> <div class="dashboard_graph">
@yield('content')
<div class="clearfix"></div>
</div> </div> </div>
<br/>
<!-- footer content --> <footer>
@include('dashboard.layouts.master.footer') @yield('footer')
</footer>
<!-- /footer content --> </div>
<!-- /page content -->
</div>
</div>
<div id="custom_notifications" class="custom-notifications dsp_none"> <ul class="list-unstyled notifications clearfix"
data-tabbed_notifications="notif-group"> </ul>
<div class="clearfix"></div>
<div id="notif-group" class="tabbed_notifications"></div> </div>
@include('dashboard.layouts.master.scripts') </body>