Skip to content
This repository has been archived by the owner on Dec 21, 2019. It is now read-only.

Commit

Permalink
Add support to request timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivan Augusto committed Aug 31, 2018
1 parent fc67c3a commit 8c76530
Show file tree
Hide file tree
Showing 7 changed files with 121 additions and 13 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.{php,phtml,json}]
indent_size = 4
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.php_cs.cache
/vendor
54 changes: 54 additions & 0 deletions .php_cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
'combine_consecutive_unsets' => true,
'method_separation' => true,
'no_multiline_whitespace_before_semicolons' => true,
'single_quote' => true,
'binary_operator_spaces' => [
'align_double_arrow' => false,
'align_equals' => false,
],
'blank_line_before_return' => true,
'braces' => [
'allow_single_line_closure' => true,
],
'concat_space' => [
'spacing' => 'one'
],
'declare_equal_normalize' => true,
'function_typehint_space' => true,
'hash_to_slash_comment' => true,
'include' => true,
'lowercase_cast' => true,
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_extra_consecutive_blank_lines' => [
'curly_brace_block',
'extra',
'parenthesis_brace_block',
'square_brace_block',
'throw',
'use',
],
'no_multiline_whitespace_around_double_arrow' => true,
'no_singleline_whitespace_before_semicolons' => true,
'no_spaces_around_offset' => true,
'no_unneeded_control_parentheses' => true,
'no_unused_imports' => true,
'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true,
'object_operator_without_whitespace' => true,
'phpdoc_align' => true,
'phpdoc_indent' => true,
'phpdoc_no_useless_inheritdoc' => true,
'phpdoc_trim' => true,
'single_blank_line_before_namespace' => true,
'ternary_operator_spaces' => true,
'trim_array_spaces' => true,
'unary_operator_spaces' => true,
'whitespace_after_comma_in_array' => true,
]);
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Se um veículo com a placa especificada for encontrado, o servidor irá retornar
- *chassi*: chassi do veículo
- *dataAtualizacaoCaracteristicasVeiculo*: data atualização das características do veículo
- *dataAtualizacaoRouboFurto*: data atualização de informações sobre roubo ou furto
- *dataAtualizacaoAlarme*:
- *dataAtualizacaoAlarme*:

Essas informações estarão disponíveis por meio de um `array associativo` ou como `atributo` do objeto.

Expand Down Expand Up @@ -110,6 +110,21 @@ $veiculo->buscar('GWW-6471', ['ip' => '177.54.144.208', 'porta' => '80']); // a
print_r($veiculo->dados());
```

## Timeout
Uma vez que o SINESP não mata sua requisição após bloqueio, é provável que você acabe se deparando com erro(s) 504. A fim de evitar transtorno, foi disponibilizado o método `timeout` para definir um tempo máximo de resposta:

```php
$veiculo->timeout(5); // tempo em segundos
```

*Dica:* Em combinação com o [proxy](#proxy) (fazendo múltiplas tentativas com diferentes proxies), isso poderá aumentar consideravelmente suas chances de sucesso para múltiplas requisições

![Múltiplos erros 504 com diferentes proxies, mas sem timeout](images/without_proxy_and_timeout.png)
*Com diferentes proxies, mas sem timeout*

![Maior parte dos 504 contornados usando proxy + timeout](images/with_proxy_and_timeout.png)
*Com diferentes proxies e timeout*

# Sinesp Python API Client

Uma implementação em linguagem `Python` encontra-se disponível no seguinte repositório: https://github.com/victor-torres/sinesp-client/
Expand Down
Binary file added images/with_proxy_and_timeout.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/without_proxy_and_timeout.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
50 changes: 38 additions & 12 deletions src/Sinesp.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ class Sinesp
private $response = '';
private $dados = [];

/**
* Time (in seconds) to wait for a response
* @var int
*/
private $timeout = null;

public function buscar($placa, array $proxy = [])
{
if ($proxy) {
Expand All @@ -20,6 +26,8 @@ public function buscar($placa, array $proxy = [])

$this->setUp($placa);
$this->exec();

return $this;
}

public function dados()
Expand All @@ -32,6 +40,18 @@ public function proxy($ip, $porta)
$this->proxy = $ip . ':' . $porta;
}

/**
* Set a timeout for request(s) that will be made
* @param int $seconds How much seconds to wait
* @return self
*/
public function timeout($seconds)
{
$this->timeout = $seconds;

return $this;
}

public function __get($name)
{
return array_key_exists($name, $this->dados) ? $this->dados[$name] : '';
Expand All @@ -53,13 +73,13 @@ private function obterResposta()
{
$xml = $this->xml();

$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"Content-length: ".strlen($xml),
);
$headers = [
'Content-type: text/xml;charset="utf-8"',
'Accept: text/xml',
'Cache-Control: no-cache',
'Pragma: no-cache',
'Content-length: ' . strlen($xml),
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
Expand All @@ -69,6 +89,11 @@ private function obterResposta()
curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
}

if ($this->timeout) {
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
}

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
Expand All @@ -80,7 +105,7 @@ private function obterResposta()

private function tratarResposta()
{
if (! $this->response) {
if (!$this->response) {
throw new \Exception('O servidor retornou nenhuma resposta!');
}

Expand All @@ -91,11 +116,11 @@ private function tratarResposta()

private function verificarRequisitos()
{
if (! function_exists('curl_init')) {
if (!function_exists('curl_init')) {
throw new \Exception('Incapaz de processar. PHP requer biblioteca cURL');
}

if (! function_exists('simplexml_load_string')) {
if (!function_exists('simplexml_load_string')) {
throw new \Exception('Incapaz de processar. PHP requer biblioteca libxml');
}

Expand All @@ -106,7 +131,7 @@ private function setUp($placa)
{
$placa = $this->ajustar($placa);

if (! $this->validar($placa)) {
if (!$this->validar($placa)) {
throw new \Exception('Placa do veiculo nao especificada ou em formato invalido!');
}

Expand All @@ -120,7 +145,7 @@ private function token()

private function xml()
{
$xml=<<<EOX
$xml = <<<EOX
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<v:Envelope xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
<v:Header>
Expand All @@ -143,6 +168,7 @@ private function xml()
</v:Body>
</v:Envelope>
EOX;

return sprintf($xml, $this->latitude(), $this->token(), $this->longitude(), strftime('%Y-%m-%d %H:%M:%S'), $this->placa);
}

Expand Down

0 comments on commit 8c76530

Please sign in to comment.