Ejemplo n.º 1
0
 public function phoneIndex($phone)
 {
     $phone = $this->device->find($phone);
     $page_title = $phone->name;
     $page_description = 'Details';
     return view('phone.index', compact('phone', 'page_title', 'page_description'));
 }
Ejemplo n.º 2
0
 public function import($devices)
 {
     $subscriptionCount = 0;
     foreach ($devices as $device) {
         if (isset($device['type']) && isset($device['address'])) {
             if (!($deviceModel = Device::find()->where(array('type' => $device['type'], 'address' => $device['address']))->one())) {
                 $deviceModel = new Device();
             }
         }
         $deviceModel->setAttributes($device);
         $identity = Yii::$app->user->identity;
         $deviceModel->user = $identity->id;
         //return $identity->id;
         if ($deviceModel->save()) {
             $deviceIndex = $deviceModel->getPrimaryKey();
             //return $deviceIndex;
             if (isset($device['services'])) {
                 //die(print_r($device['services'],true));
                 $subscriptionCount += Service::import($device['services'], $deviceIndex);
             }
         }
         /*else {
               return $deviceModel->getErrors();
           }*/
         return $subscriptionCount;
     }
 }
Ejemplo n.º 3
0
 /**
  * Store device to our db
  *
  */
 public function store($userId, $device = null)
 {
     if ($device == null) {
         $device = new Device(['device_uuid' => \Request::get('device_uuid'), 'model' => \Request::get('model'), 'manufacturer' => \Request::get('manufacturer'), 'user_id' => $userId]);
     }
     $device->save();
     return $device;
 }
Ejemplo n.º 4
0
 public static function newDevice($userId, $deviceName, $deviceToken)
 {
     $device = new Device();
     $device->user_id = $userId;
     $device->device_name = $deviceName;
     $device->device_token = $deviceToken;
     $device->created_at = Carbon::now()->toDateTimeString();
     $device->save();
     return $device;
 }
 /**
  * Updates an existing TaskDefined model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $model = $this->findModel($id);
     $modelDevice = new Device();
     $modelAction = new Action();
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         //return $this->redirect(['view', 'id' => $model->id]);
         return $this->redirect(['task/index']);
     } else {
         return $this->render('update', ['model' => $model, 'from_device_ids' => ArrayHelper::map($modelDevice->getDeviceMaster(), 'id', 'name'), 'to_device_ids' => ArrayHelper::map($modelDevice->getDeviceAll(), 'id', 'name'), 'action_ids' => ArrayHelper::map($modelAction->getActionAll(), 'id', 'name')]);
     }
 }
Ejemplo n.º 6
0
 static function createIfNew($domain, $node, $lat, $lng, $address = null)
 {
     $dev = self::find()->where(['domain' => $domain, 'node' => $node])->one();
     if (!$dev) {
         $dev = new Device();
         $dev->domain = $domain;
         $dev->node = $node;
         $dev->lat = $lat;
         $dev->lng = $lng;
         $dev->address = $address;
         $dev->save();
     }
 }
Ejemplo n.º 7
0
 /**
  * Execute the job.
  *
  * @return void
  */
 public function handle()
 {
     //Create the Phone
     $phone = Phone::firstOrCreate(['name' => $this->device['DeviceName'], 'description' => $this->device['Description'], 'model' => $this->device['Model']]);
     // Create the IpAddress
     $ipAddress = IpAddress::firstOrCreate(['ip_address' => $this->device['IpAddress']]);
     // Attach the Phone and IpAddress
     $phone->ipAddresses()->sync([$ipAddress->id], false);
     //Start creating Eraser
     $tleObj = Eraser::create(['device_id' => $phone->id, 'ip_address_id' => $ipAddress->id, 'type' => $this->device['type']]);
     if (isset($this->device['bulk_id'])) {
         $tleObj->bulks()->attach($this->device['bulk_id']);
     }
     if ($this->device['IpAddress'] == "Unregistered/Unknown") {
         $tleObj->result = 'Fail';
         $tleObj->fail_reason = 'Unregistered/Unknown';
         $tleObj->save();
     }
     $keys = setKeys($this->device['Model'], $this->device['type']);
     if (!$keys) {
         $tleObj->result = 'Fail';
         $tleObj->fail_reason = 'Unsupported Model';
         $tleObj->save();
         \Log::debug('Bulk', [$tleObj]);
         return;
     }
     $dialer = new PhoneDialer($tleObj, $this->cluster);
     $status = $dialer->dial($keys);
     //Successful if returned true
     $passFail = $status ? 'Success' : 'Fail';
     $tleObj->result = $passFail;
     $tleObj->save();
 }
 public function actionDeleteDevice()
 {
     $id = Yii::$app->request->get('id');
     if (isset($id) and !empty($id)) {
         $device = Device::findOne($id);
         $device ? $device->delete() : '';
     }
     Yii::$app->session->setFlash('message', 'Delete Success !');
     return $this->redirect([Url::to('list-device')]);
 }
Ejemplo n.º 9
0
 public function updateDevice(Request $request, $dev_key)
 {
     $model = Device::where('dev_key', '=', $dev_key)->first();
     $status = $request->input('status');
     if ($status !== null) {
         $model->status = $request->input('status');
         $model->save();
     }
     return response()->json($model);
 }
Ejemplo n.º 10
0
 private function clean()
 {
     foreach ($this->results[static::INVALID] as $token) {
         Device::wherePlatform('android')->whereToken($token)->delete();
     }
     foreach ($this->results[static::UPDATED] as $token => $new_token) {
         $device = Device::wherePlatform('android')->whereToken($token)->first();
         $device->token = $new_token;
         $device->save();
     }
 }
Ejemplo n.º 11
0
 protected function getDeviceById($deviceId)
 {
     if ($this->dontNeedAuth) {
         $device = Device::where('id', $deviceId)->first();
     } else {
         $device = Device::where('id', $deviceId)->where('user_id', $this->currentSession->user_id)->first();
     }
     if (empty($device) || $device->isDisabled()) {
         throw new \Exception('Device is not registered or disabled', 201);
     }
     return $device;
 }
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Device::find();
     $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;
     }
     $query->andFilterWhere(['id' => $this->id, 'master' => $this->master, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at]);
     $query->andFilterWhere(['like', 'name', $this->name]);
     return $dataProvider;
 }
Ejemplo n.º 13
0
 /**
  * Send push notifications
  *
  * @param Request $request
  * @return Response
  */
 public function postPush(Request $request)
 {
     if (!$this->appKeyAvailable($request)) {
         return $this->notAuthorized($request);
     }
     if ($this->isSessionEmpty($request)) {
         $this->setResultError("Session token is missing", 401);
     } elseif ($this->setSessionUser($request)) {
         $validator = Validator::make($request->all(), ['data' => 'array', 'data.message' => 'required', 'users' => 'required|array', 'users.0' => 'required|numeric']);
         if ($validator->fails()) {
             $this->setResultError($validator->messages(), 400);
         } else {
             $android_devices = Device::whereEnvironment(getenv('ANDROID_PUSH_ENVIRONMENT'))->wherePlatform('android')->whereIn('user_id', $request->get('users'))->get();
             $android_tokens = array();
             foreach ($android_devices as $android_device) {
                 $android_tokens[] = $android_device->token;
             }
             $ios_devices = Device::whereEnvironment(getenv('IOS_PUSH_ENVIRONMENT'))->wherePlatform('ios')->whereIn('user_id', $request->get('users'))->get();
             $ios_tokens = array();
             foreach ($ios_devices as $ios_device) {
                 $ios_tokens[$ios_device->token] = $ios_device->created_at;
             }
             $data = $request->get('data');
             $message = $data['message'];
             unset($data['message']);
             $result = ['android' => ['sent' => 0, 'invalid' => 0, 'unknown' => 0], 'ios' => ['sent' => 0, 'invalid' => 0, 'unknown' => 0]];
             if (!empty($android_tokens)) {
                 $android = new AndroidPushNotifications();
                 $android->data = $data;
                 $android->message = $message;
                 $android->devices = $android_tokens;
                 $result['android'] = $android->push();
             }
             if (!empty($ios_tokens)) {
                 $ios = new iOSPushNotifications();
                 $ios->data = $data;
                 $ios->message = $message;
                 $ios->devices = $ios_tokens;
                 $result['ios'] = $ios->push();
             }
             $this->setResultOk($result);
         }
     } else {
         $this->setResultError("Mismatched session token", 401);
     }
     return $this->setResponse();
 }
Ejemplo n.º 14
0
 public static function device($parameter = "")
 {
     $from = \Carbon\Carbon::now()->modify('-3 month');
     $to = \Carbon\Carbon::now();
     if ($parameter == "") {
         return Md\Device::count();
     }
     if ($parameter == "trial") {
         return Md\Device::where(function ($query) use($from, $to) {
             $query->whereBetween('created_at', array($from, $to));
         })->count();
     }
     if ($parameter == "active") {
         return Md\Device::where(function ($query) use($from, $to) {
             $query->whereBetween('created_at', array($from, $to))->Where('created_at', '<=', $from);
         })->count();
     }
 }
 public function actionImport()
 {
     ini_set('memory_limit', '5G');
     if (isset($_POST['data'])) {
         $data = $_POST['data'];
     } else {
         $data = gzcompress(json_encode(array()));
     }
     //die(json_encode(($data)));
     $unzippedData = $data;
     //gzuncompress($data);
     $arrayData = json_decode($unzippedData, true);
     //if(isset($arrayData['devices']))
     //{
     $subscriptionCount = Device::import($arrayData);
     return 'total number of subscriptions made:' . $subscriptionCount;
     //}
     return $arrayData;
 }
Ejemplo n.º 16
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Device::find();
     $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;
     }
     $query->joinWith('user');
     // Join table foreign key
     // $query->andFilterWhere([
     //     'devices.id' => $this->id,
     // ]);
     $query->andFilterWhere(['like', 'devices.id', $this->id]);
     // like with ID
     if (!isset($params['sort'])) {
         $query->orderBy(['id' => SORT_DESC]);
     }
     $query->andFilterWhere(['like', 'device_code', $this->device_code])->andFilterWhere(['like', 'users.email', $this->user_id]);
     return $dataProvider;
 }
Ejemplo n.º 17
0
 public function getDevices()
 {
     return $this->hasMany(Device::className(), ['user_id' => 'user_id']);
 }
Ejemplo n.º 18
0
 /**
  * Validate the observation data before performing any action
  *
  */
 private function validateObservation()
 {
     $response = new ApiResponse();
     if (!\Request::has('device_uuid')) {
         $response->status = 'error';
         $response->message = ['id' => '', 'code' => 'device_uuid_null', 'description' => 'The device uuid should not be null'];
     } else {
         $device = Device::where('device_uuid', \Request::get('device_uuid'))->first();
         if ($device == null) {
             $response->status = 'error';
             $response->message = ['id' => '', 'code' => 'device_not_found', 'description' => 'The device could not be found'];
         }
     }
     if (!\Request::has('mission_id')) {
         $response->status = 'error';
         $response->message = ['id' => '', 'code' => 'mission_id_null', 'description' => 'The mission id should not be null'];
     } else {
         //check that the mission_id exists
         $this->mission = Mission::with('type')->find(\Request::get('mission_id'));
         if ($this->mission == null) {
             $response->status = 'error';
             $response->message = ['id' => '', 'code' => 'mission_id_not_found', 'description' => 'The requested mission could not be found'];
         }
     }
     if (\Request::has('observation_date')) {
         if (!$this->validateDate(\Request::get('observation_date'))) {
             $response->status = 'error';
             $response->message = ['id' => '', 'code' => 'wrong_date_format', 'description' => 'The date should be in the following format: Y-m-d hh:mm:ss'];
         }
     }
     if (\Request::has('latitude') && !is_numeric(\Request::get('latitude')) || \Request::has('longitude') && !is_numeric(\Request::get('longitude'))) {
         $response->status = 'error';
         $response->message = ['id' => '', 'code' => 'coordinates_not_numeric', 'description' => 'The coordinates of the observation should be numeric'];
     }
     if (!\Request::has('measurements')) {
         $response->status = 'error';
         $response->message = ['id' => '', 'code' => 'measurements_null', 'description' => 'The measurements should not be null'];
     } else {
         foreach (\Request::get('measurements') as $measurement) {
             if (!isset($measurement['latitude']) || $measurement['latitude'] == '' || !isset($measurement['longitude']) || $measurement['longitude'] == '') {
                 $response->status = 'error';
                 $response->message = ['id' => '', 'code' => 'coordinates_null', 'description' => 'The coordinates of the measurements should not be null'];
             } else {
                 if (!is_numeric($measurement['latitude']) || !is_numeric($measurement['longitude'])) {
                     $response->status = 'error';
                     $response->message = ['id' => '', 'code' => 'coordinates_not_numeric', 'description' => 'The coordinates of the measurements should be numeric'];
                 }
             }
         }
     }
     return $response;
 }
 /**
  * Создание новой связи  a new UserLinkDev model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new UserLinkDev();
     // нужно выполнить проверку запроса
     if ($model->load(Yii::$app->request->post())) {
         /* это кусок учитывает только одно условие  sys_n
         	 
         			$device = Device::find()
         							->where(['sys_n' => $model->sysn])
         							->one();
         			
         	*/
         $device = Device::find()->where(['sys_n' => $model->sysn])->andFilterWhere(['AND', 'imei', $model->imei])->one();
         if ($device !== null) {
             // throw new NotFoundHttpException('нашли !!! ура'  );
         } else {
             // УСТРОЙСТВО С ТАКИМ SYSN И imei   НЕ НАЙДЕНО!!!
             // throw new NotFoundHttpException('22222222222');
             return $this->render('notdev', ['model' => $device]);
         }
         //--
         $model->created_at = time();
         $model->id_user = Yii::$app->user->identity->id;
         // id текущего юзера
         $model->id_device = $device->id;
         if ($model->dev_name == null) {
             $model->dev_name = 'Устройство без названия';
         }
         $model->save();
         // Устройство успешно добавленно!!!
         return $this->render('add-ok', ['model' => $device]);
         //return $this->redirect(['index', 'id' => $model->id]);
         //return $this->redirect(['view', 'id' => $model->id]);
     } else {
         return $this->render('create', ['model' => $model]);
     }
 }
Ejemplo n.º 20
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getDevice0()
 {
     return $this->hasOne(Device::className(), ['id' => 'device']);
 }
 /**
  * Finds the Device model based on its primary key value.
  * If the model is not found, a 404 HTTP exception will be thrown.
  * @param integer $id
  * @return Device the loaded model
  * @throws NotFoundHttpException if the model cannot be found
  */
 protected function findModel($id)
 {
     if (($model = Device::findOne($id)) !== null) {
         return $model;
     } else {
         throw new NotFoundHttpException('The requested page does not exist.');
     }
 }
Ejemplo n.º 22
0
 public function postList()
 {
     $userId = $this->currentSession->user_id;
     return array('data' => Device::where('user_id', $userId)->get());
 }
Ejemplo n.º 23
0
 /**
  * Run the database seeds.
  * Use php artisan db:seed to run the seed files.
  *
  * @return void
  */
 public function run()
 {
     $user = User::create(['name' => 'admin', 'email' => '*****@*****.**', 'password' => Hash::make('1q2w3e')]);
     Device::create(['device_uuid' => 'test', 'model' => 'test', 'manufacturer' => 'test', 'user_id' => $user->id]);
     $user->roles()->attach([1]);
 }
Ejemplo n.º 24
0
 public function getDeviceAll()
 {
     return Device::find()->asArray()->all();
 }
 public function fundDeviceSysnImei($sys_n, $imei)
 {
     if (($model = Device::findOne(['sys_n' => $sys_n, 'imei' => $imei])) !== null) {
         return $model;
     } else {
         throw new NotFoundHttpException('The requested page does not exist.');
     }
 }
Ejemplo n.º 26
0
 public function getDevicesAll()
 {
     return ArrayHelper::map(Device::find()->asArray()->all(), 'id', 'name');
 }
Ejemplo n.º 27
0
 function addPortToDevice($portNode, $uniPortType, $deviceId, $deviceName, $netNode, $domainName)
 {
     $deviceNodes = $this->xpath->query(".//x:Node", $netNode);
     if ($deviceNodes) {
         foreach ($deviceNodes as $deviceNode) {
             if ($deviceId == $deviceNode->getAttribute('id')) {
                 $relationNodes = $this->xpath->query(".//x:Relation", $deviceNode);
                 if ($relationNodes) {
                     foreach ($relationNodes as $relationNode) {
                         if ($relationNode->getAttribute("type") == $uniPortType) {
                             $relationNode->appendChild($portNode->cloneNode());
                             return;
                         }
                     }
                 }
                 return;
             }
         }
     }
     $deviceNode = $netNode->appendChild($this->xml->createElementNS('http://schemas.ogf.org/nml/2013/05/base#', 'Node'));
     $deviceNode->setAttribute("id", $deviceId);
     $name = $deviceNode->appendChild($this->xml->createElementNS('http://schemas.ogf.org/nml/2013/05/base#', 'name'));
     $name->appendChild($this->xml->createTextNode($deviceName));
     $relation = $deviceNode->appendChild($this->xml->createElementNS('http://schemas.ogf.org/nml/2013/05/base#', 'Relation'));
     $relation->setAttribute("type", "http://schemas.ogf.org/nml/2013/05/base#hasInboundPort");
     $relation = $deviceNode->appendChild($this->xml->createElementNS('http://schemas.ogf.org/nml/2013/05/base#', 'Relation'));
     $relation->setAttribute("type", "http://schemas.ogf.org/nml/2013/05/base#hasOutboundPort");
     $location = Device::findLocation($domainName, $deviceName);
     if ($location) {
         $locationNode = $deviceNode->appendChild($this->xml->createElement('location'));
         $lat = $locationNode->appendChild($this->xml->createElement('latitude'));
         $lat->appendChild($this->xml->createTextNode($location['lat']));
         $lng = $locationNode->appendChild($this->xml->createElement('longitude'));
         $lng->appendChild($this->xml->createTextNode($location['lng']));
         $address = $locationNode->appendChild($this->xml->createElement('address'));
         $address->appendChild($this->xml->createTextNode(urlencode($location['address'])));
     }
     $relationNodes = $this->xpath->query(".//x:Relation", $deviceNode);
     if ($relationNodes) {
         foreach ($relationNodes as $relationNode) {
             if ($relationNode->getAttribute("type") == $uniPortType) {
                 $relationNode->appendChild($portNode->cloneNode());
                 return;
             }
         }
     }
 }
Ejemplo n.º 28
0
 public function actionListDevice()
 {
     $devices = Device::find()->all();
     return Json::encode($devices);
 }
Ejemplo n.º 29
0
 public function getChartData()
 {
     /*echo('getChartDateFromTo<pre>');
     		print_r($this->getChartDateFromTo());
     		echo('</pre>');
     		echo('$this->device_id: ' . $this->device_id) . '<br/>' . PHP_EOL;
     		echo('$this->action_id: ' . $this->action_id) . '<br/>' . PHP_EOL;
     		echo('$this->getChartIntervalGroupBy(): ' . $this->getChartIntervalGroupBy()) . '<br/>' . PHP_EOL;*/
     /*$tasks = Task::find()
     		->select([
     			'id',
     			'from_device_id',
     			'to_device_id',
     			'action_id',
     			'data',
     			'created_at',
     			"SUBSTRING_INDEX(data, ';', 1) AS temp",
     			"SUBSTRING_INDEX(SUBSTRING_INDEX(data, ';', 2), ';', -1) AS hum",
     			"AVG(SUBSTRING_INDEX(data, ';', 1)) AS avgTemp",
     			"AVG(SUBSTRING_INDEX(SUBSTRING_INDEX(data, ';', 2), ';', -1)) AS avgHum",
     		])
     		->where([
     			'from_device_id' => '1',
     			'to_device_id' => $this->device_id,
     			'action_id' => $this->action_id,
     		])
     		->andwhere(['between', 'created_at', $this->getChartDateFromTo()['from'], $this->getChartDateFromTo()['to']])
     		->groupBy($this->getChartIntervalGroupBy())
     		->orderBy('created_at')
     		->asArray()
     		->all();*/
     $taskmodel = new Task();
     $devicemodel = new Device();
     $tasks = $taskmodel->getTaskBetweenDate($this->getChartDateFromTo(), $devicemodel->getDeviceMaster()[0]['id'], $this->device_id, $this->action_id);
     /*echo('$tasks: <pre>');
     		print_r($tasks);
     		echo('</pre>');*/
     //echo('date(Y-m-d 00:00:00);: ' . date('Y-m-d')) . '<br/>' . PHP_EOL;
     /*echo('$this->getChartDateFromTo():<pre>');
     		print_r($this->getChartDateFromTo());
     		echo('</pre>');*/
     //SUBSTRING_INDEX(`data`, `;`, 1) as temp)
     /*echo('$tasks<pre>');
     		print_r($tasks);
     		echo('</pre>');*/
     /*
     * chart: {
                 type: 'line'
             },
             title: {
                 text: 'Fruit Consumption'
             },
             xAxis: {
                 categories: ['Apples', 'Bananas', 'Oranges']
             },
             yAxis: {
                 title: {
                     text: 'Fruit eaten'
                 }
             },
             series: [{
                 name: 'Jane',
                 data: [1, 0, 4]
             }, {
                 name: 'John',
                 data: [5, 7, 3]
             }]
     */
     $chart = ['chart' => ['type' => $this->chart_type], 'title' => ['text' => 'Temperature / Humidity ' . $this->getChartDate()[$this->chart_date]]];
     $xAxis = [];
     $yAxis = [['title' => ['text' => 'Temperature'], 'labels' => ['format' => '{value}']], ['title' => ['text' => 'Humidity'], 'labels' => ['format' => '{value}'], 'opposite' => true]];
     /*echo('$yAxis<pre>');
     		print_r($yAxis);
     		echo('</pre>');*/
     $series = [];
     //$series[] = ['name' => 'Temperature', 'data' => []];
     //$series[] = ['name' => 'Humidity', 'data' => []];
     $series = [['yAxis' => 0, 'name' => 'Temperature', 'data' => array()], ['yAxis' => 1, 'name' => 'Humidity', 'data' => array()]];
     foreach ($tasks as $key => $task) {
         $xAxis['categories'][] = date('H', strtotime($task['created_at']));
         //$series[0]['data'][] = $task['avgTemp'];
         $series[0]['data'][] = number_format((double) $task['data']['t'], 2, '.', '');
         //$series[1]['data'][] = $task['avgHum'];
         $series[1]['data'][] = number_format((double) $task['data']['h'], 2, '.', '');
     }
     // create from the data a string (for highcharts to read the values good, its a javascript thing)
     //$series[0]['data'] = '[' . implode(',', $series[0]['data']) . ']';
     //$series[1]['data'] = '[' . implode(',', $series[1]['data']) . ']';
     /*echo('$xAxis<pre>');
     		print_r($xAxis);
     		echo('</pre>');*/
     /*echo('$series<pre>');
     		print_r($series);
     		echo('</pre>');*/
     /*$options = array_merge($chart, array('xAxis' => $xAxis), array('yAxis' => $yAxis), array('series' => $series));
     		echo('$options<pre>');
     		print_r($options);
     		echo('</pre>');*/
     return [$chart, $xAxis, $yAxis, $series];
 }
Ejemplo n.º 30
0
 function cleanDB()
 {
     if (!empty($this->results[static::INVALID])) {
         Device::wherePlatform('ios')->whereEnvironment(getenv('IOS_PUSH_ENVIRONMENT'))->whereIn('token', $this->results[static::INVALID])->delete();
     }
 }