get logs from device

This commit is contained in:
dongpd 2020-10-15 11:20:21 +07:00
parent 4a33ee9a7d
commit 53de75104e
11 changed files with 376 additions and 59 deletions

View File

@ -240,61 +240,13 @@ class DepartmentController extends Controller {
}
public function actionTest() {
$timezone = [
"DeviceIP" => "192.168.1.200",
"TimezoneId" => 1,
"SunTime1" => 0, "SunTime2" => 0, "SunTime3" => 0,
"MonTime1" => 0, "MonTime2" => 0, "MonTime3" => 0,
"TueTime1" => 0, "TueTime2" => 0, "TueTime3" => 0,
"WedTime1" => 0, "WedTime2" => 0, "WedTime3" => 0,
"ThuTime1" => 0, "ThuTime2" => 0, "ThuTime3" => 0,
"FriTime1" => $this->convertTime("8:30", "12:30"), "FriTime2" => $this->convertTime("13:30", "18:30"), "FriTime3" => 0,
"SatTime1" => 0, "SatTime2" => 0, "SatTime3" => 0,
"Hol1Time1" => 0, "Hol1Time2" => 0, "Hol1Time3" => 0,
"Hol2Time1" => 0, "Hol2Time2" => 0, "Hol2Time3" => 0,
"Hol3Time1" => 0, "Hol3Time2" => 0, "Hol3Time3" => 0
];
$timezoneRq = $this->requestToMCard("/SetDeviceData/timezone", $timezone);
$user = [
"DeviceIP" => "192.168.1.200",
"CardNo" => 16673827,
"Pin" => 69,
"Password" => "",
"Group" => "",
"StartTime" => "",
"EndTime" => ""
];
$userRq = $this->requestToMCard("/SetDeviceData/user", $user);
$userAuthor = [
"DeviceIP" => "192.168.1.200",
"Pin" => 69,
"AuthorizeTimezoneId" => 1,
"AuthorizeDoorId" => 2
];
$userAuthorRq = $this->requestToMCard("/SetDeviceData/userauthorize", $userAuthor);
return var_dump($timezoneRq, $userRq, $userAuthorRq);
}
public function requestToMCard($path, $data) {
return file_get_contents("http://192.168.2.119:2001" . $path, false, stream_context_create([
'http' => [
'header' => "Content-Type: application/json",
'method' => "POST",
'content' => json_encode($data)
]
]));
}
public function convertTime($from, $to) {
$fTemp = explode(":", $from);
$front = dechex(intval($fTemp[0]) * 100 + intval($fTemp[1]));
$tTemp = explode(":", $to);
$back = dechex(intval($tTemp[0]) * 100 + intval($tTemp[1]));
return hexdec("0" . $front . "0" . $back);
$datas = json_decode(common::requestToCardService("/GetDeviceData/GetLog", [
"DeviceIP" => "192.168.1.200"
]), true);
echo "<pre>";
var_dump($datas);
echo "</pre>";
exit();
}
}

View File

@ -15,6 +15,7 @@ use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Html;
use yii\helpers\Url;
use app\models\Logs;
/**
* DeviceController implements the CRUD actions for Device model.
@ -338,7 +339,7 @@ class DeviceController extends Controller {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
return [
"title" => Html::tag("i", "", ["class" => "fa fa-exchange"]) . " Đồng bộ dữ liệu đến thiết bị",
"title" => Html::tag("i", "", ["class" => "fa fa-refresh"]) . " Đồng bộ dữ liệu đến thiết bị",
"form" => $this->renderPartial("sync"),
"lists" => Yii::$app->request->post("lists")
];
@ -444,4 +445,36 @@ class DeviceController extends Controller {
}
}
public function actionGetLogs() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
return [
"title" => Html::tag("i", "", ["class" => "fa fa-exchange"]) . " Lấy các sự kiện",
"form" => $this->renderPartial("logs"),
"lists" => Yii::$app->request->post("lists")
];
}
}
public function actionSyncLogs() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
$device = $this->findModel(Yii::$app->request->post("data"));
$response = json_decode(common::requestToCardService("/GetDeviceData/GetLog", ["DeviceIP" => $device->ip_address]), true);
$datas = [];
foreach ($response as $key => $value) {
if ($value["Cardno"] !== "0")
$datas[] = [$value["Pin"], $value["Cardno"], $device->id, $value["DoorID"], $value["InOutState"], Logs::parseTime($value["Time_second"]), $value["EventType"]];
}
$model = new Logs();
if ($model->multiCreate($datas)) {
common::requestToCardService("/DeleteDeviceData/DeleteLog", ["DeviceIP" => $device->ip_address]);
}
return [
"totals" => count($datas),
"IP" => $device->ip_address
];
}
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace app\controllers;
use Yii;
use app\models\Logs;
use app\models\LogsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* LogsController implements the CRUD actions for Logs model.
*/
class LogsController extends Controller {
public function init() {
parent::init();
if (Yii::$app->user->isGuest)
return $this->redirect(['/site/login']);
}
/**
* {@inheritdoc}
*/
public function behaviors() {
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
public function actionIndex() {
$this->view->title = 'Sự kiện hôm nay';
$searchModel = new LogsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
protected function findModel($id) {
if (($model = Logs::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}

77
models/Logs.php Normal file
View File

@ -0,0 +1,77 @@
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "logs".
*
* @property int $id
* @property int $staff_id
* @property int $card_number
* @property int $device_id
* @property int $door_id
* @property int $in_out_state
* @property int $time
* @property int $event_type
*/
class Logs extends \yii\db\ActiveRecord {
/**
* {@inheritdoc}
*/
public static function tableName() {
return 'logs';
}
/**
* {@inheritdoc}
*/
public function rules() {
return [
[['staff_id', 'device_id', 'door_id', 'in_out_state', 'time', 'event_type', 'card_number'], 'integer'],
[['device_id', 'door_id', 'in_out_state', 'time', 'event_type', 'card_number'], 'required'],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels() {
return [
'id' => 'ID',
'staff_id' => 'Staff ID',
'card_number' => 'card_number',
'device_id' => 'Device ID',
'door_id' => 'Door ID',
'in_out_state' => 'In Out State',
'time' => 'Time',
'event_type' => 'Event Type',
];
}
public function multiCreate($datas) {
$field = ['staff_id', 'card_number', 'device_id', 'door_id', 'in_out_state', 'time', 'event_type'];
static::getDb()->createCommand()->batchInsert($this->tableName(), $field, $datas)->execute();
return true;
}
public static function parseTime($time) {
$temp = intval($time);
$second = $temp % 60;
$temp = $temp / 60;
$minute = $temp % 60;
$temp = $temp / 60;
$hour = $temp % 24;
$temp = $temp / 24;
$day = $temp % 31 + 1;
$temp = $temp / 31;
$month = $temp % 12 + 1;
$temp = $temp / 12;
$year = $temp + 2000;
$timeFull = sprintf("%02d", $hour) . ":" . sprintf("%02d", $minute) . ":" . sprintf("%02d", $second) . " " . sprintf("%02d", $day) . "/" . sprintf("%02d", $month) . "/" . intval($year);
return date_format(date_create_from_format('H:i:s d/m/Y', $timeFull), 'U');
}
}

72
models/LogsSearch.php Normal file
View File

@ -0,0 +1,72 @@
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Logs;
/**
* LogsSearch represents the model behind the search form of `app\models\Logs`.
*/
class LogsSearch extends Logs
{
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id', 'staff_id', 'device_id', 'door_id', 'in_out_state', 'time', 'event_type'], 'integer'],
];
}
/**
* {@inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Logs::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'staff_id' => $this->staff_id,
'device_id' => $this->device_id,
'door_id' => $this->door_id,
'in_out_state' => $this->in_out_state,
'time' => $this->time,
'event_type' => $this->event_type,
]);
return $dataProvider;
}
}

View File

@ -35,8 +35,8 @@ use yii\widgets\ActiveForm;
Kiểm soát truy cập
</a>
</li>
<li>
<a href="#">
<li class="<?php if (in_array($this->context->id, ['logs'])) echo "active"; ?>">
<a href="<?php echo \yii\helpers\Url::to(['/logs']); ?>">
Báo cáo
</a>
</li>

View File

@ -33,6 +33,15 @@
['label' => 'Cấp quyền truy cập', 'url' => ['/assign'], 'icon' => 'cogs']
];
}
if (in_array($this->context->id, ['logs'])) {
$items = [
['label' => 'Sự kiện hôm nay', 'url' => ['/logs'], 'icon' => 'clock-o'],
['label' => 'Sự kiện 3 ngày gần đây', 'url' => ['/logs/3-days'], 'icon' => 'calendar'],
['label' => 'Sự kiện tuần này', 'url' => ['/logs/this-week'], 'icon' => 'calendar'],
['label' => 'Sự kiện tuần trước', 'url' => ['/logs/last-week'], 'icon' => 'calendar'],
['label' => 'Tất cả', 'url' => ['/logs/all'], 'icon' => 'calendar']
];
}
?>
<?=
dmstr\widgets\Menu::widget(

View File

@ -9,6 +9,7 @@
<input type='hidden' name='get_data_sync_url' value="{Url::to(['get-data-sync'])}">
<input type='hidden' name='sync_schedule_url' value="{Url::to(['sync-schedule'])}">
<input type='hidden' name='sync_staffs_url' value="{Url::to(['sync-staffs'])}">
<input type='hidden' name='get_logs_sync_url' value="{Url::to(['sync-logs'])}">
<div class="" style="font-size: 15px;">
<label class="action-button" onclick="common.form(this, 'device');" data-href="{Url::to(['create'])}">
<i class="fa fa-plus-square fa-1-5x"></i> Thêm
@ -19,11 +20,14 @@
<label class="action-button" onclick="_delete(this);" data-href="{Url::to(['delete'])}">
<i class="fa fa-trash fa-1-5x"></i> Xóa
</label>
<label class="action-button" onclick="_getLogs(this);" data-href="{Url::to(['get-logs'])}">
<i class="fa fa-exchange fa-1-5x"></i> Lấy các sự kiện
</label>
<label class="action-button" onclick="_form(this);" data-href="{Url::to(['change-ip'])}">
<i class="fa fa-pencil fa-1-5x"></i> Thay đổi địa chỉ IP
</label>
<label class="action-button" onclick="_sync(this);" data-href="{Url::to(['sync'])}">
<i class="fa fa-exchange fa-1-5x"></i> Đồng bộ dữ liệu đến thiết bị
<i class="fa fa-refresh fa-1-5x"></i> Đồng bộ dữ liệu đến thiết bị
</label>
<label class="action-button" onclick="_export(this);" data-href="{Url::to(['export'])}">
<i class="fa fa-download fa-1-5x"></i> Xuất

13
views/device/logs.tpl Normal file
View File

@ -0,0 +1,13 @@
<div class="well" style="height: 300px;overflow-y: scroll;" id="logs-response">
</div>
<div class="progress">
<div class="progress-bar progress-bar-primary progress-bar-striped" id='progress' role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
0%
</div>
</div>
<div class="text-right">
<button class="btn btn-default" data-dismiss="modal" disabled="" id="close-modal">
<span class="fa fa-remove"></span> Đóng
</button>
</div>

38
views/logs/index.tpl Normal file
View File

@ -0,0 +1,38 @@
{extends file=$smarty.current_dir|cat:'/../extends.tpl'}
{use class="yii\helpers\Url"}
{use class="yii\grid\GridView"}
{use class="yii\widgets\Pjax" type="block"}
{use class="app\assets\DepartmentAsset"}
{DepartmentAsset::register($this)|void}
{block name='content'}
<div class="logs-index">
<div class="" style="font-size: 15px;">
<label class="action-button" onclick="common.form(this, '');" data-href="{Url::to(['tree'])}">
<i class="fa fa-sitemap fa-1-5x"></i> Cây thư mục
</label>
<label class="action-button" onclick="_logs(this);" data-href="{Url::to(['logs'])}">
<i class="fa fa-file fa-1-5x"></i> Ghi nhận hệ thống
</label>
</div>
{Pjax id="department-list"}
{GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'layout'=> \app\helpers\CommonGrid::getLayout(),
'tableOptions' => [
'class' => 'table table-striped table-bordered table-hover',
'style' => 'background:#fff;min-width:700px;'
],
'columns' => [
[
'class' => 'yii\grid\SerialColumn',
'contentOptions' => ['class' => 'text-center'],
'headerOptions' => ['class' => 'text-center', 'style' => 'width:3%']
],
'time',
'staff_id'
]
])}
{/Pjax}
</div>
{/block}

View File

@ -373,3 +373,66 @@ function syncStaffs(data, ip) {
}
});
}
var progressLogs = 0;
var totalsLogs = 0;
function _getLogs(e) {
var lists = [];
$.each($("input[name='checkbox-device']:checked"), function () {
lists.push($(this).val());
});
if (lists.length == 0) {
alert("Vui lòng lựa chọn đối tượng!");
return;
}
common.modalBlock(true);
$.ajax({
url: $(e).attr('data-href'),
type: 'POST',
data: {
lists: lists
},
success: function (data) {
common.modalBlock(false);
common.modalOpen(data.form, false, data.title);
$("#close-modal").attr("disabled", true);
$("#modalHeader").find("button").remove();
totalsLogs = data.lists.length;
for (var i = 0; i < data.lists.length; i++) {
syncLogs(data.lists[i]);
}
},
error: function (jqXHR, textStatus, errorThrown) {
common.modalBlock(false);
common.ajaxError();
}
});
}
function syncLogs(data) {
$.ajax({
url: $("input[name='get_logs_sync_url']").val(),
type: 'POST',
data: {
data: data
},
success: function (data) {
var html = "";
html = "<span class='text-green'><i class='fa fa-check'></i> Đồng bộ thành công <b>" + data.totals + "</b> sự kiện từ thiết bị <b>" + data.IP + "</b>.</span><br>";
$("#logs-response").append(html);
progressLogs++;
var percent = parseInt(progressLogs / totalsLogs * 100);
$("#progress").attr("aria-valuenow", percent);
$("#progress").attr("style", "width: " + percent + "%");
$("#progress").html(percent + "%");
if (percent >= 100) {
progressLogs = 0;
$("#close-modal").attr("disabled", false);
}
},
error: function (jqXHR, textStatus, errorThrown) {
common.ajaxError();
}
});
}