Skip to content
This repository has been archived by the owner on Aug 9, 2021. It is now read-only.

Commit

Permalink
feat: maintain online status of devices
Browse files Browse the repository at this point in the history
  • Loading branch information
btry committed Jul 26, 2017
1 parent 46f603f commit 84be562
Show file tree
Hide file tree
Showing 5 changed files with 209 additions and 1 deletion.
9 changes: 9 additions & 0 deletions inc/agent.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,8 @@ public function prepareInputForAdd($input) {
break;
}

unset($input['is_online']);

return $input;
}

Expand Down Expand Up @@ -722,6 +724,13 @@ public function getSearchOptions() {
$tab[$i]['datatype'] = 'string';
$tab[$i]['massiveaction'] = false;

$i++;
$tab[$i]['table'] = self::getTable();
$tab[$i]['field'] = 'is_online';
$tab[$i]['name'] = __('online', "flyvemdm");
$tab[$i]['datatype'] = 'boolean';
$tab[$i]['massiveaction'] = false;

return $tab;
}

Expand Down
36 changes: 35 additions & 1 deletion inc/mqtthandler.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ public static function getInstance() {
return self::$instance;
}

/**
* Maintains a MQTT topic to publish the current version of the backend
*
* @param unknown $mqtt
*/
protected function publishManifest($mqtt) {
// Don't use version from the constant in setup.php because the backend may upgrade while this script is running
// thus keep in RAM in an older version
Expand Down Expand Up @@ -104,7 +109,7 @@ public function pingresp(sskaje\mqtt\MQTT $mqtt, sskaje\mqtt\Message\PINGRESP $p
public function publish(sskaje\mqtt\MQTT $mqtt, sskaje\mqtt\Message\PUBLISH $publish_object) {
$topic = $publish_object->getTopic();
$message = $publish_object->getMessage();
$this->log->saveIngoingMqttMessage($topic, $publish_object->getMessage());
$this->log->saveIngoingMqttMessage($topic, $message);

$mqttPath = explode('/', $topic, 5);
if (isset($mqttPath[4])) {
Expand All @@ -118,6 +123,8 @@ public function publish(sskaje\mqtt\MQTT $mqtt, sskaje\mqtt\Message\PUBLISH $pub
$this->deleteAgent($topic, $message);
} else if ($mqttPath[4] == "Status/Inventory") {
$this->updateInventory($topic, $message);
} else if ($mqttPath[4] == "Status/Online") {
$this->updateOnlineStatus($topic, $message);
} else if ($mqttPath[4] == "FlyvemdmManifest/Status/Version") {
$this->updateAgentVersion($topic, $message);
} else if (strpos($topic, "/FlyvemdmManifest") === 0) {
Expand Down Expand Up @@ -262,4 +269,31 @@ protected function saveGeolocationPosition($topic, $message) {
$this->updateLastContact($topic, $message);
}
}

/**
* Update the status of a task from a notification sent by a device
*
* @param string $topic
* @param string $essage
*/
protected function updateOnlineStatus($topic, $message) {
$agent = new PluginFlyvemdmAgent();
if ($agent->getByTopic($topic)) {
$feedback = json_decode($message, true);
if (!isset($feedback['online'])) {
return;
}
if ($feedback['online'] == 'no') {
$status = '0';
} else {
$status = '1';
}
$agent->update([
'id' => $agent->getID(),
'is_online' => $status,
]);

$this->updateLastContact($topic, $message);
}
}
}
1 change: 1 addition & 0 deletions install/mysql/plugin_flyvemdm_empty.sql
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ CREATE TABLE IF NOT EXISTS `glpi_plugin_flyvemdm_agents` (
`plugin_flyvemdm_fleets_id` int(11) DEFAULT NULL,
`last_report` datetime DEFAULT NULL,
`last_contact` datetime DEFAULT NULL,
`is_online` tinyint(1) NOT NULL DEFAULT '0',
`certificate` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Expand Down
1 change: 1 addition & 0 deletions install/upgrade/update_to_dev.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,5 @@ function plugin_flyvemdm_update_to_dev(Migration $migration) {

$migration->setVersion(PLUGIN_FLYVEMDM_VERSION);

$migration->addField(PluginFlyvemdmAgent::getTable(), 'is_online', 'integer', ['after' => 'last_contact']);
}
163 changes: 163 additions & 0 deletions tests/0010_Integration/HandleIncomingMqttMessageTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
<?php
/*
LICENSE
Copyright (C) 2016 Teclib'
Copyright (C) 2010-2016 by the FusionInventory Development Team.
This file is part of Flyve MDM Plugin for GLPI.
Flyve MDM Plugin for GLPi is a subproject of Flyve MDM. Flyve MDM is a mobile
device management software.
Flyve MDM Plugin for GLPI is free software: you can redistribute it and/or
modify it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Flyve MDM Plugin for GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Flyve MDM Plugin for GLPI. If not, see http://www.gnu.org/licenses/.
------------------------------------------------------------------------------
@author Thierry Bugier Pineau
@copyright Copyright (c) 2016 Flyve MDM plugin team
@license AGPLv3+ http://www.gnu.org/licenses/agpl.txt
@link https://github.com/flyve-mdm/flyve-mdm-glpi
@link http://www.glpi-project.org/
------------------------------------------------------------------------------
*/

class HandleIncomingMqttMessageTest extends RegisteredUserTestCase
{
protected static $entity;

protected static $invitation;

protected static $guestEmail;

protected static $guestUser;

protected static $agent;

protected static $defaultFleet;

protected static $fleet;

public static function setUpBeforeClass() {
parent::setUpBeforeClass();

self::login('glpi', 'glpi', true);
self::$entity = new Entity();
self::$entity->add([
'name' => "to be deleted",
]);
$entityId = self::$entity->getID();

self::$guestEmail = 'a.user@localhost.local';

// create invitation
self::$invitation = new PluginFlyvemdmInvitation();
self::$invitation->add([
'entities_id' => $entityId,
'_useremails' => self::$guestEmail,
]);

self::$guestUser = new User();
self::$guestUser->getFromDB(self::$invitation->getField('users_id'));

Session::destroy();
self::setupGLPIFramework();

// Login as guest user
$_REQUEST['user_token'] = User::getToken(self::$invitation->getField('users_id'), 'api_token');
self::login('', '', false);
unset($_REQUEST['user_token']);

// enroll an agent
self::$agent = new PluginFlyvemdmAgent();
self::$agent->add([
'entities_id' => $entityId,
'_email' => self::$guestEmail,
'_invitation_token' => self::$invitation->getField('invitation_token'),
'_serial' => 'AZERTY',
'csr' => '',
'firstname' => 'John',
'lastname' => 'Doe',
'version' => '1.0.0',
]);

Session::destroy();
self::setupGLPIFramework();

// login as super admin
self::login('glpi', 'glpi', true);

//find default fleet
self::$defaultFleet = new PluginFlyvemdmFleet();
self::$defaultFleet->getFromDBByQuery("WHERE `entities_id` = '$entityId' AND `is_default` <> '0'");

// create a fleet
self::$fleet = new PluginFlyvemdmFleet();
self::$fleet->add([
'name' => 'a fleet',
'entities_id' => $entityId,
]);

//move the agent to the fleet
self::$agent->update([
'id' => self::$agent->getID(),
'plugin_flyvemdm_fleets_id' => self::$fleet->getID(),
]);

}

/**
*
* Check the agent is marked online when the backend is notified about
*
* @return void
*/
public function testDeviceGoesOnline() {
$this->DeviceOnlineStatus(self::$agent, 'yes', 1);
}

/**
* Check the device is marked offline when the backend is notified about
*
* @depends testDeviceGoesOnline
*
* @return void
*/
public function testDeviceGoesOffline() {
$this->DeviceOnlineStatus(self::$agent, 'no', 0);
}

protected function DeviceOnlineStatus($agent, $mqttStatus, $expectedStatus) {
$topic = $agent->getTopic() . '/Status/Online';

// prepare mock
$message = ['online' => $mqttStatus];
$messageEncoded = json_encode($message, JSON_OBJECT_AS_ARRAY);
$mqttStub = $this->getMockBuilder(sskaje\mqtt\MQTT::class)
->disableOriginalConstructor()
->getMock();
$publishStub = $this->getMockBuilder(sskaje\mqtt\Message\PUBLISH::class)
->disableOriginalConstructor()
->setMethods(['getTopic', 'getMessage'])
->getMock();
$publishStub->method('getTopic')
->willReturn($topic);
$publishStub->method('getMessage')
->willReturn($messageEncoded);

$mqttHandler = PluginFlyvemdmMqtthandler::getInstance();
$mqttHandler->publish($mqttStub, $publishStub);

// refresh the agent
$agent->getFromDB($agent->getID());
$this->assertEquals($expectedStatus, $agent->getField('is_online'));
}

}

0 comments on commit 84be562

Please sign in to comment.