Proyecto

General

Perfil

Descargar (18,7 KB) Estadísticas
| Rama: | Revisión:
//#define DEBUG_SIATIC

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "time.h"
#include <QMessageBox>
#include <stdio.h>
#include <QtConcurrent>
#ifdef WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include <QProcessEnvironment>
#include <QTime>
#include <QTimer>
#include <globales.h>
#define ROUTER_CONNECT_TIMEOUT 7000
int ESTADO_WIFI=0;
int RECONECTAR=0;
int RELEno=0;
Globales opciones;


/*
* Management Window UI
* for classroom devices management based on Qt
*
* @author: Alejandro Antúnez Reino, SODITEC S.L
*/

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{

ui->setupUi(this);
ui->checkBox->setChecked(true);
ui->checkBox->setVisible(false);
ui->label_8->setText("");
CONTADOR = new QTime();
// Set a fixed size for the current window
setFixedSize(this->size());

//qDebug() << "iniciando ventanas";
// Prepares the UI for correct sizing...
layout()->setContentsMargins(0,0,0,0);
centerText();

// Get the port name for the device...
QFile *devNameFile;
opciones.cargaVariablesEntorno();
#ifdef _WIN32
QString fileName(std::getenv("appdata"));
fileName += "\\SiaticConfig\\devPortName.cfg";
fileName.replace('\\', '/');
devNameFile = new QFile(fileName);
if (!devNameFile->exists()) { QMessageBox::information(this, "Error", "Error en la configuracion del proyector, servicio no disponible, por favor contacte con el responsable TIC del centro."); exit (-1); }
devNameFile->open(QFile::ReadWrite);
QString devPortName(devNameFile->readAll());
devPortName = devPortName.remove('\n') ;
devNameFile->close();
#else
QString devPortName(opciones.puertoProyector());
#endif

// Initialize the projector connection protocol...
this->projectorManagement = new OptomaProjectorManagement(this, devPortName);
ui->wifiSwitch->setEnabled(false);
ui->wifiSwitch->setDisabled(true);
ui->genClave->setDisabled(true);
#ifdef _WIN32
ui->genClave->setDisabled(true);
#else
ui->genClave->setVisible(false);
#endif
// Initialize the DLINK Password API
if (Globales::getPuntoAccesoActivo() =="1"){
//qDebug()<<"getPuntoAccesoActivo 1";
dlinkPwdGen = new DLinkPasswordGen();
dlinkPwdGen->HOST_ROUTER=opciones.IP();
dlinkPwdGen->USER_DEFAULT=opciones.queRoot();
dlinkPwdGen->PWD_DEFAULT=opciones.claveRoot();
connect(dlinkPwdGen, SIGNAL(onWifiStateAsyncResponse(bool)), this, SLOT(onRouterWifiStateResponse(bool)));
connect(dlinkPwdGen, SIGNAL(onWifiSSIDAsyncResponse(QString)), this, SLOT(onRouterWifiSSIDResponse(QString)));
connect(dlinkPwdGen, SIGNAL(onWifiPassAsyncResponse(QString)), this, SLOT(onRouterWifiPassResponse(QString)));
dlinkPwdGen->ConnectRouter();
Conectando.start(ROUTER_CONNECT_TIMEOUT);
connect(&Conectando,SIGNAL(timeout()),this,SLOT(IntentarConectar()));
}else{
ui->wifiSwitch->setEnabled(false);
ui->genClave->setEnabled(false);

}
this->redRelayDevice = new RedRelayLibrary();
if (!this->redRelayDevice->ConnectRelay()){ // If we can't connect to the relay , show a message and close the app.
QMessageBox::information(this, "Problema de conexión",
"Debe haber algún problema al conectar con el dispositivo de control, por favor, contacte con el administrador inmediatamente. A partir de ahora la funcionalidad será limitada");

#ifndef DEBUG_SIATIC
//exit(-1);
disableRelayButtons();
#endif
}else{
RELEno=1;
//Evito el sindrome del Rele Apagado
redRelayDevice->SetRelayState(ON,(RelayPort) WIFI_PORT);
}

char* str = (char*) QString("amixer -c 1 set Master %1%").arg(QString::number(volumen)).toLatin1().data();
//qDebug() << str;
system(str);

connect(projectorManagement, SIGNAL(ProjectorStatusReceived(bool)), this, SLOT(projectorStatusReceived(bool)));
#ifdef _WIN32
ui->projectorFrozenLBL->setVisible(false);
ui->projectorOnLBL->setVisible(false);
ui->projectorOffLBL->setVisible(true);
ui->safeProjectorSwitch->setText("No Responde");
#else
connect(projectorManagement, SIGNAL(IsAliveResponse(bool)), this, SLOT(isAliveResponse(bool)));
#endif
connect(this, SIGNAL(turnOnSignal()), this, SLOT(turnOnProjector()));
connect(this, SIGNAL(turnOffSignal()), this, SLOT(turnOffProjector()));
connect(this, SIGNAL(updateDevicesSignal()), this, SLOT(updateDevicesSlot()));
projectorManagement->OpenConnection();
updateDevicesState();
}

QString MainWindow::getLabelForState(bool State){
if (State) return "Apagar";
else return "Encender";
}

void MainWindow::projectorStatusReceived(bool Status){
switch (LastPWRStatusRequest){
case 0: // Switch safely request
QtConcurrent::run(this, &MainWindow::switchSafely, Status);
break;
case 1: // Request for power state
updateUiProjectorPWRState(Status);
break;
}
LastPWRStatusRequest = -1;
}

void MainWindow::disableRelayButtons(){
ui->soundOnLBL->setVisible(false);
ui->soundOffLBL->setVisible(true);
ui->heightOffLBL->setVisible(true);
ui->heightOnLBL->setVisible(false);
ui->audioSwitch->setEnabled(false);
ui->upHSwitch->setEnabled(false);
ui->downHSwitch->setEnabled(false);
ui->volUp->setEnabled(false);
ui->volDown->setEnabled(false);
}

void MainWindow::onRouterWifiStateResponse(bool estado){
if(!estado){
ui->label_7->setVisible(false);
ui->label_8->setVisible(false);
ui->checkBox->setVisible(false);
}
else{
ui->checkBox->setVisible(true);
if(ui->checkBox->isChecked()){
ui->label_7->setVisible(false);
ui->label_8->setVisible(true);
}
else{
ui->label_7->setVisible(true);
ui->label_8->setVisible(false);
}
}
ESTADO_WIFI = estado ? 1 : 0;
setWifiSwitchState(ESTADO_WIFI);
updateDevicesState();
dlinkPwdGen->QuePassAsync();
}

void MainWindow::onRouterWifiSSIDResponse(QString SSID){
if (msg != NULL) { msg->close(); delete msg; msg = NULL; }
dlinkPwdGen->HayWifiAsync();
ui->label_2->setText(SSID);
/*QString clave="Clave: ";
clave += dlinkPwdGen->GetSystemPWD();

ui->label_7->setText(clave);*/
ui->wifiSwitch->setEnabled(true);
ui->wifiSwitch->setDisabled(false);
ui->genClave->setDisabled(false);
}

void MainWindow::onRouterWifiPassResponse(QString Pass){
QString clave="Clave: ";
clave += Pass;
ui->label_7->setText(clave);
ui->label_8->setText("Clave: ********");
}

void MainWindow::updateUiProjectorPWRState(bool State){
setProjectorSwitchState(State);
}

void MainWindow::turnOffProjector(){
ui->safeProjectorSwitch->setEnabled(false);
setProjectorSwitchState(false);
projectorManagement->TurnOff();
}

void MainWindow::turnOnProjector(){
ui->safeProjectorSwitch->setEnabled(false);
setProjectorSwitchState(true);
projectorManagement->TurnOn();
}


void MainWindow::updateDevicesSlot(){
ui->safeProjectorSwitch->setEnabled(true);
updateDevicesState();
}

void MainWindow::switchSafely(bool PWRStatus){
if (PWRStatus){
emit turnOffSignal();
}else{
emit turnOnSignal();
}//Retardo del Apagado
QThread::sleep(20);
emit updateDevicesSignal();
}

void MainWindow::setWifiSwitchState(bool State){
ui->wifiSwitch->setText(getLabelForState(State));
ui->wifiONLBL->setVisible(State);
ui->wifiOffLBL->setVisible(!State);

}

void MainWindow::setProjectorSwitchState(bool State){
ui->safeProjectorSwitch->setText(getLabelForState(State));
ui->projectorOnLBL->setVisible(State);
ui->projectorOffLBL->setVisible(!State);
ui->projectorFrozenLBL->setVisible(freze);
ui->videoFreezeButton->setDisabled(!State);
ui->videoUnfreezeButton->setDisabled(!State);
}

void MainWindow::setSoundSwitchState(bool State){
if(RELEno==1){
ui->audioSwitch->setText(getLabelForState(State));
ui->soundOnLBL->setVisible(State);
ui->soundOffLBL->setVisible(!State);
}
}

void MainWindow::setHeightSwitchState(bool State){
if(RELEno==1){
ui->heightOnLBL->setVisible(State);
ui->heightOffLBL->setVisible(!State);
}
}

void MainWindow::updateDevicesState(){
if(RELEno==1){
setSoundSwitchState(redRelayDevice->GetRelayState((RelayPort)SOUND_PORT) == ON);
setHeightSwitchState(redRelayDevice->GetRelayState((RelayPort)MOTOR_PORT) == ON);
}

setWifiSwitchState(ESTADO_WIFI);


if (ui->safeProjectorSwitch->isEnabled()){
LastPWRStatusRequest = 1;
projectorManagement->GetPowerState();
}
}

MainWindow::~MainWindow()
{
delete ui;
delete redRelayDevice;
delete dlinkPwdGen;
delete CONTADOR;
delete projectorManagement;
}

void MainWindow::centerText(){
ui->label_2->setGeometry((width()/2) - 250, 5, 500, 40);
#ifdef WIN32
ui->label_8->setGeometry((width()/2) - 250,45,500,50);
ui->label_7->setGeometry((width()/2) - 250,45,500,100);//x,y,ancho,alto
//ui->label_7->adjustSize();
#else
ui->label_8->setGeometry((width()/2) - 250,43,500,60);
ui->label_7->setGeometry((width()/2) - 250,43,500,60);
#endif

}

void MainWindow::resizeEvent(QResizeEvent *event){
centerText();
}

void MainWindow::on_audioSwitch_clicked()
{
redRelayDevice->SetRelayState(redRelayDevice->GetRelayState((RelayPort) SOUND_PORT) == ON ? OFF : ON,
(RelayPort) SOUND_PORT);
updateDevicesState();
}

void MainWindow::motorSwitch()
{
redRelayDevice->SetRelayState(redRelayDevice->GetRelayState((RelayPort) MOTOR_PORT) == ON ? OFF : ON,
(RelayPort) MOTOR_PORT);
updateDevicesState();
}

void MainWindow::notificacionEspera(bool Activar)
{
if(Activar){
msg = new QProgressDialog("Activando la Wifi del Aula. Espere unos segundos, por favor","Cerrar",0,0,this);
}else{
msg = new QProgressDialog("Desactivando la Wifi del Aula. Espere unos segundos, por favor","Cerrar",0,0,this);
}
msg->setWindowFlags(msg->windowFlags() | Qt::FramelessWindowHint);

msg->setStyleSheet("border: 4px solid #2196F3; border-radius: 3px;");
foreach (QObject *obj, msg->children()){
if (!obj->isWidgetType()) continue;
QWidget *wdg = (QWidget*) obj;
wdg->setStyleSheet("border: 0px");
}

msg->setCancelButton(NULL);
msg->setWindowModality(Qt::WindowModal);
msg->show();
}

void MainWindow::on_wifiSwitch_clicked()
{
ui->wifiSwitch->setDisabled(true);
//qDebug()<<"BOTON WIFI pulsado";
if (dlinkPwdGen == NULL || !dlinkPwdGen->Ready){
QMessageBox::information(this, "Error", "Error de controladora SIATIC, servicio no disponible, por favor contacte con el responsable TIC del centro.");
ui->wifiSwitch->setEnabled(false);
ui->wifiSwitch->setDisabled(true);
ui->genClave->setDisabled(true);
Conectando.start(ROUTER_CONNECT_TIMEOUT);
return;
}
if(ESTADO_WIFI==0){//Conecto wifi
ui->label_8->setHidden(false);
ui->checkBox->setHidden(false);

notificacionEspera(true);
dlinkPwdGen->ConectarWIFI();
ESTADO_WIFI=1;
}else{//Desconecto
ui->label_8->setHidden(true);
ui->checkBox->setHidden(true);
notificacionEspera(false);
dlinkPwdGen->DesconectarWIFI();
ESTADO_WIFI=0;
}

dlinkPwdGen->Ready=false;

RECONECTAR=1;
Conectando.start(ROUTER_CONNECT_TIMEOUT);
updateDevicesState();
}

void MainWindow::on_upHSwitch_pressed()
{
if (redRelayDevice->GetRelayState((RelayPort)MOTOR_PORT) == OFF)
motorSwitch();
redRelayDevice->SetRelayState(OFF,
(RelayPort) MOTOR_UP_PORT);
}

void MainWindow::isAliveResponse(bool alive){
if (!alive){
setProjectorSwitchState(false);
if(ui->safeProjectorSwitch->isEnabled()){
ui->safeProjectorSwitch->setDisabled(true);
QMessageBox::information(this, "Error", "Error de comunicación con el proyector, servicio no disponible, por favor contacte con el responsable TIC del centro.");
}
}
}

void MainWindow::on_upHSwitch_released()
{
redRelayDevice->SetRelayState(ON,
(RelayPort) MOTOR_UP_PORT);
}

void MainWindow::on_downHSwitch_pressed()
{
if (redRelayDevice->GetRelayState((RelayPort)MOTOR_PORT) == OFF)
motorSwitch();
redRelayDevice->SetRelayState(OFF,
(RelayPort) MOTOR_DOWN_PORT);
}

void MainWindow::on_downHSwitch_released()
{
redRelayDevice->SetRelayState(ON,
(RelayPort) MOTOR_DOWN_PORT);
}

void MainWindow::on_volUp_clicked()
{
#ifndef _WIN32
if (volumen < 100) volumen += 10;
system((char*) QString("amixer -c 1 set Master %1%").arg(QString::number(volumen)).toLatin1().data());
#else
SendMessageW((HWND) this->winId(),0x319,(WPARAM) this->winId(), 0xA0000);
#endif
}

void MainWindow::on_volDown_clicked()
{
#ifndef _WIN32
if (volumen > 0) volumen -= 10;
system((char*) QString("amixer -c 1 set Master %1%").arg(QString::number(volumen)).toLatin1().data());
#else
SendMessageW((HWND) this->winId(),0x319,(WPARAM) this->winId(), 0x90000);
#endif
}

void MainWindow::on_safeProjectorSwitch_clicked()
{
freze=false;
// We make a async request for op 0
LastPWRStatusRequest = 0;
projectorManagement->GetPowerState();
}

void MainWindow::on_shutdownEverything_clicked()
{
QMessageBox::StandardButton confirmacion;
confirmacion = QMessageBox::question(this, "APAGAR TODO", "¿Realmente desea, Apagar todo?",
QMessageBox::Yes|QMessageBox::No);
if (confirmacion == QMessageBox::Yes) {
if (Globales::getPuntoAccesoActivo()=="1"){
//qDebug()<<"getPuntoAccesoActivo 1";
if (dlinkPwdGen == NULL || !dlinkPwdGen->Ready){
ui->wifiSwitch->setEnabled(false);
ui->wifiSwitch->setDisabled(true);
ui->genClave->setDisabled(true);
QThread::sleep(1);
}

dlinkPwdGen->DesconectarWIFI();
ESTADO_WIFI=0;
Conectando.start(ROUTER_CONNECT_TIMEOUT);
}

freze=false;
redRelayDevice->SetRelayState(OFF,
(RelayPort) SOUND_PORT);
updateDevicesState();
if (ui->projectorOnLBL->isVisible()){
LastPWRStatusRequest = 0;
projectorManagement->GetPowerState();
}
QProgressDialog mensaje("Apagando todos los dispositivos. Espere, por favor.","Cerrar",0,20000,this);
CONTADOR->start();
mensaje.setCancelButton(NULL);
mensaje.setWindowModality(Qt::WindowModal);
while(CONTADOR->elapsed()<20000){
mensaje.setValue(CONTADOR->elapsed());
QThread::usleep(5000);
}
}
}

void MainWindow::on_videoFreezeButton_clicked()
{
setWindowState(Qt::WindowMinimized);
this->projectorManagement->Freeze();
freze=true;
updateDevicesState();
}

void MainWindow::on_videoUnfreezeButton_clicked()
{
setWindowState(Qt::WindowMaximized);
this->projectorManagement->Unfreeze();
freze=false;
updateDevicesState();

}

void MainWindow::IntentarConectar(){
if(dlinkPwdGen->Ready){
//qDebug()<<"Conectado";
IMPOSIBLE = 7;
dlinkPwdGen->QueSsidAsync();
Conectando.stop();
}else{
//qDebug()<<"Reintentando";
disconnect(dlinkPwdGen, SIGNAL(onWifiStateAsyncResponse(bool)), this, SLOT(onRouterWifiStateResponse(bool)));
disconnect(dlinkPwdGen, SIGNAL(onWifiSSIDAsyncResponse(QString)), this, SLOT(onRouterWifiSSIDResponse(QString)));
disconnect(dlinkPwdGen, SIGNAL(onWifiPassAsyncResponse(QString)), this, SLOT(onRouterWifiPassResponse(QString)));
dlinkPwdGen->DisconnectRouter();
delete dlinkPwdGen;
if(IMPOSIBLE<=0){
if (msg != NULL) { msg->close(); delete msg; msg = NULL; }
QMessageBox::information(this, "Error", "Error del Punto de Acceso, servicio no disponible, por favor contacte con el responsable TIC del centro.");
Conectando.stop();
return;
}
dlinkPwdGen = new DLinkPasswordGen();
dlinkPwdGen->HOST_ROUTER=opciones.IP();
dlinkPwdGen->USER_DEFAULT=opciones.queRoot();
dlinkPwdGen->PWD_DEFAULT=opciones.claveRoot();
connect(dlinkPwdGen, SIGNAL(onWifiStateAsyncResponse(bool)), this, SLOT(onRouterWifiStateResponse(bool)));
connect(dlinkPwdGen, SIGNAL(onWifiSSIDAsyncResponse(QString)), this, SLOT(onRouterWifiSSIDResponse(QString)));
connect(dlinkPwdGen, SIGNAL(onWifiPassAsyncResponse(QString)), this, SLOT(onRouterWifiPassResponse(QString)));
dlinkPwdGen->ConnectRouter();
IMPOSIBLE--;
}
}


void MainWindow::on_genClave_clicked()
{

int i, aux;
char key[9] = "";
srand(time(NULL));
for(i=0; i<4; i++){
if(i==0){
aux=rand()%26;
key[i]=(char)(aux+'a');
key[i+4]=(char)(aux+'a');
}else{
aux=rand()%10;
key[i]=(char)(aux+'0');
key[i+4]=(char)(aux+'0');
}
}
dlinkPwdGen->GeneratePWD(opciones.queRoot() , opciones.claveRoot() , key);
//qDebug()<<"pulsado clave"<<key;
ui->genClave->setDisabled(true);
ui->wifiSwitch->setEnabled(false);
ui->wifiSwitch->setDisabled(true);
ui->label_7->setVisible(false);
ui->label_8->setVisible(false);
QProgressDialog mensaje("Generando nueva clave Wifi para el Aula. Espere, por favor.","Cerrar",0,80000,this);
CONTADOR->start();
mensaje.setCancelButton(NULL);
mensaje.setWindowModality(Qt::WindowModal);
while(CONTADOR->elapsed()<50000){
mensaje.setValue(CONTADOR->elapsed());
}
dlinkPwdGen->DisconnectRouter();
QThread::sleep(1);
dlinkPwdGen->ConnectRouter();

Conectando.start(5000);
}

void MainWindow::on_checkBox_stateChanged(int arg1){
if(arg1){
ui->label_7->setVisible(false);
ui->label_8->setVisible(true);
}
else{
ui->label_7->setVisible(true);
ui->label_8->setVisible(false);
}
}
(21-21/45)