wialon 1.2.1 → 2.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (3) hide show
  1. checksums.yaml +4 -4
  2. data/lib/wialon.rb +175 -193
  3. metadata +1 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c468b5adac754601ead67242a4996a7b1c3af2d95484175bd481fb44618a97eb
4
- data.tar.gz: b89f3da4f7817a8677858e70a4a3ef6208c61382edbca7bc2cc2baef2d04c816
3
+ metadata.gz: 0ed7252fcc81139620337bbf452c2b72c61bb531f9c7ecbd81e3bf8a088a4aae
4
+ data.tar.gz: e39f71251095a4d557977321bd64ceeace8403eb0681d6883bc7b409a6ac3f84
5
5
  SHA512:
6
- metadata.gz: 3ab37f8e399efb71ae589c26e63d2c8769a68468f3e461788516c281af39c8ae0a5fa5a5dddae90eddf8d026b5f41eea0d303fff1eb720e3ab74b576b4cb285d
7
- data.tar.gz: 93208ff60ea8932d9df111ecd4b8cc10162a9e78669d78effdef090084d0db2877e2d753300ddd2e3bfbece4fe2963d15a50944a59ad8069edf89cb028aa0286
6
+ metadata.gz: 85d460361e1684dbb4d79f90675957c0c5c43820f67220097448008f5b9bc75b66710569ec96bdedd0154e90810707f4f4f06a3ee4db05f78a2e3fea7d6547cf
7
+ data.tar.gz: 4b547340fa10108ded011dd09249f5507b8c0ffa0a1b7ec1a368caa99e274ca90d0e8e2e61bc83d95d9529f559e490174b7cf7000543e015ad976b83d154306b
@@ -1,227 +1,209 @@
1
- class Wialon
2
- require 'json'
3
- require 'net/http'
4
- require 'uri'
5
-
6
- # Variables
7
- attr_accessor :sid, :base_api_url, :default_params, :uid, :host, :scheme, :debug
8
-
9
- # Class constructor
10
- def initialize(debug = false, scheme = 'https', host = 'hst-api.wialon.com', port = 0, sid = '', extra_params = {})
11
- self.debug = debug
12
- self.sid = ''
13
- self.scheme = scheme
14
- self.default_params = {}
15
- self.default_params.replace(extra_params)
16
- self.host = host
17
- self.base_api_url = "#{scheme}://#{host}#{((port > 0) ? ":" + port.to_s : "")}/wialon/ajax.html?"
18
- self.uid = ''
19
- end
1
+ ## WialonSDK class
2
+ module Wialon
3
+ class Sdk
4
+ require 'json'
5
+ require 'net/http'
6
+ require 'uri'
7
+
8
+ attr_accessor :session_id, :base_url, :default_params, :user_id, :host, :is_development
9
+
10
+ def initialize(is_development = false, scheme = 'https', host = 'hst-api.wialon.com', port = 0, session_id = '', extra_params = {})
11
+ self.is_development = is_development
12
+ self.session_id = session_id
13
+ self.host = host
14
+
15
+ self.default_params = {}
16
+ self.default_params.replace(extra_params)
17
+
18
+ if port < 0
19
+ raise SdkException.new('Invalid port, must be greater than 0')
20
+ elsif port.to_i > 0
21
+ self.base_url = "#{scheme}://#{host}:#{port}"
22
+ else
23
+ self.base_url = "#{scheme}://#{host}"
24
+ end
20
25
 
21
- def get_address(lat, lon, flags = 1255211008)
22
- if self.debug
23
- puts "URL: #{'https://geocode-maps.wialon.com/' + self.host + '/gis_geocode?coords=[' + JSON.generate({"lon": lon,"lat": lat}) + ']&flags=' + flags.to_s + '&uid=' + self.uid.to_s}"
26
+ self.base_url += '/wialon/ajax.html?'
27
+ self.user_id = 0
24
28
  end
25
- uri = URI.parse('https://geocode-maps.wialon.com/' + self.host + '/gis_geocode?coords=[' + JSON.generate({"lon": lon,"lat": lat}) + ']&flags=' + flags.to_s + '&uid=' + self.uid.to_s)
26
- request = Net::HTTP::Post.new(uri)
27
- req_options = { use_ssl: (uri.scheme == "https") }
28
- response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
29
- http.request(request)
30
- end
31
- return JSON.parse(response.body)[0]
32
- end
33
29
 
34
- def get_coordinates(string)
35
- string = string.split(" ").join(" ")
36
- from = "ÀÁÂÃÄÅàáâãäåĀāĂ㥹ÇçĆćĈĉĊċČčÐðĎďĐđÈÉÊËèéêëĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħÌÍÎÏìíîïĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłÑñŃńŅņŇňʼnŊŋÒÓÔÕÖØòóôõöøŌōŎŏŐőŔŕŖŗŘřŚśŜŝŞşŠšſŢţŤťŦŧÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųŴŵÝýÿŶŷŸŹźŻżŽž"
37
- to = "AAAAAAaaaaaaAaAaAaCcCcCcCcCcDdDdDdEEEEeeeeEeEeEeEeEeGgGgGgGgHhHhIIIIiiiiIiIiIiIiIiJjKkkLlLlLlLlLlNnNnNnNnnNnOOOOOOooooooOoOoOoRrRrRrSsSsSsSssTtTtTtUUUUuuuuUuUuUuUuUuUuWwYyyYyYZzZzZz"
38
- string = string.tr(from,to)
39
-
40
- uri = URI.parse('https://search-maps.wialon.com/' + self.host + '/gis_searchintelli?phrase=' + string + '&count=1&indexFrom=0&uid=' + self.uid.to_s)
41
- request = Net::HTTP::Post.new(uri)
42
- req_options = { use_ssl: (uri.scheme == "https") }
43
- response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
44
- http.request(request)
45
- end
46
-
47
- return JSON.parse(response.body)
48
- end
49
-
50
- def call_without_svc_parse(action, args)
51
- # Set local variable with base url
52
- url = self.base_api_url
53
-
54
- # Set params
55
- params = {'svc': action.to_s, 'params': JSON.generate(args), 'sid': self.sid}
56
-
57
- # Replacing global params with local params
58
- all_params = self.default_params.replace(params)
59
-
60
- if self.debug
61
- puts "========="
62
- puts "Query URL: #{url} - Params: #{all_params}"
63
- puts "========="
64
- puts "#{url}&svc=#{action.to_s}&params=#{JSON.generate(args)}&sid=#{self.sid}"
65
- puts "========="
66
- end
30
+ def reverse_geocoding(latitude, longitude, flags=1255211008)
31
+ coordinates = JSON.generates({latitude: latitude, longitude: longitude})
32
+ url = "https://geocode-maps.wialon.com/#{self.host}/gis_geocode?coords=[#{coordinates}]&flags=#{flags}&uid=#{self.user_id}"
67
33
 
68
- uri = URI.parse(url)
69
-
70
- # Curl request
71
- request = Net::HTTP::Post.new(uri)
34
+ if self.is_development
35
+ self.debug_printer("Method: Reverse geocoding service\nURL: #{url}")
36
+ end
72
37
 
73
- request.set_form_data(
74
- "svc" => action.to_s,
75
- "params" => JSON.generate(args),
76
- "sid" => self.sid
77
- )
38
+ begin
39
+ uri = URI.parse(url)
40
+ rescue Exception => e
41
+ raise SdkException.new("Internal error: #{e}")
42
+ end
78
43
 
79
- req_options = { use_ssl: (uri.scheme == "https") }
44
+ request = Net::HTTP::Post.new(uri)
80
45
 
81
- response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
82
- http.request(request)
83
- end
84
-
85
- response = JSON.parse(response.body)
46
+ begin
47
+ response = Net::HTTP.start(uri.hostname, uri.port, { use_ssl: uri.scheme == 'https' }) do |http|
48
+ http.request(request)
49
+ end
50
+ rescue Exception => e
51
+ raise SdkException.new("Internal error: #{e}")
52
+ end
86
53
 
87
- return response
88
- end
54
+ begin
55
+ response = JSON.parse(response.body)
56
+ rescue Exception => e
57
+ raise SdkException.new("Internal error: #{e}")
58
+ end
89
59
 
90
- # RemoteAPI request performer
91
- # action: RemoteAPI command name
92
- # args: JSON string with request parameters
93
- def call(action, args)
94
- # Set local variable with base url
95
- url = self.base_api_url
96
-
97
- # Set params
98
- params = {'svc': action.to_s.sub('_', '/'), 'params': JSON.generate(args), 'sid': self.sid}
99
-
100
- # Replacing global params with local params
101
- all_params = self.default_params.replace(params)
102
-
103
- if self.debug
104
- puts "========="
105
- puts "Query URL: #{url} - Params: #{all_params}"
106
- puts "========="
107
- puts "#{url}&svc=#{action.to_s.sub('_', '/')}&params=#{JSON.generate(args)}&sid=#{self.sid}"
108
- puts "========="
60
+ return response[0]
109
61
  end
110
62
 
111
- uri = URI.parse(url)
112
-
113
- # Curl request
114
- request = Net::HTTP::Post.new(uri)
63
+ def login(token)
64
+ result = self.token_login({ token: token })
115
65
 
116
- request.set_form_data(
117
- "svc" => action.to_s.sub('_', '/'),
118
- "params" => JSON.generate(args),
119
- "sid" => self.sid
120
- )
66
+ self.user_id = result['user']['id']
67
+ self.session_id = result['eid']
121
68
 
122
- req_options = { use_ssl: (uri.scheme == "https") }
69
+ return result
70
+ end
123
71
 
124
- response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
125
- http.request(request)
72
+ def logout
73
+ self.core_logout
74
+ return nil
126
75
  end
127
76
 
128
- response = JSON.parse(response.body, symbolize_names: true)
77
+ def set_session_id(session_id)
78
+ self.session_id = session_id
79
+ end
129
80
 
130
- if response.class == Hash
131
- if !response[:error].nil?
132
- return {
133
- status: 400,
134
- reason: parse_errors(response[:error]),
135
- result: response
136
- }
137
- end
81
+ def get_session_id
82
+ return self.session_id
138
83
  end
139
84
 
140
- return {
141
- status: 200,
142
- result: response
143
- }
144
- end
85
+ protected
86
+ def call(method_name, args)
87
+ svc = ''
88
+ if method_name.to_s == 'unit_group_update_units'
89
+ svc = 'unit_group/update_units'
90
+ else
91
+ svc = method_name.to_s.sub('_', '/')
92
+ end
145
93
 
146
- def login(token)
147
- result = self.token_login({token: token})
148
- if !result[:result][:eid].nil?
149
- self.sid = result[:result][:eid]
150
- end
94
+ begin
95
+ parameters = JSON.generate(args)
96
+ rescue Exception => e
97
+ raise SdkException.new("Internal error: #{e}")
98
+ end
151
99
 
152
- begin
153
- if !result[:result][:user][:id].nil?
154
- self.uid = result[:result][:user][:id]
155
- end
156
- rescue Exception => e
157
- if self.debug
158
- puts "Error in login: #{e}"
159
- end
160
- end
161
- return result
162
- end
100
+ parameters = {
101
+ svc: svc,
102
+ params: parameters,
103
+ sid: self.session_id
104
+ }
163
105
 
164
- def logout
165
- result = self.core_logout({})
166
- if result.empty? && result[:result][:error] == 0
167
- self.sid = ""
168
- end
169
- return result
170
- end
106
+ url = "#{self.base_url}svc=#{parameters[:svc]}&params=#{parameters[:params]}&sid=#{parameters[:sid]}"
107
+ if self.is_development
108
+ self.debug_printer("Method: #{svc}\nParameters: #{parameters}\nURL: #{url}")
109
+ end
110
+
111
+ begin
112
+ uri = URI.parse(url)
113
+ rescue Exception => e
114
+ raise SdkException.new("Internal error: #{e}")
115
+ end
116
+
117
+ request = Net::HTTP::Post.new(uri)
118
+ request.set_form_data(
119
+ 'svc' => parameters[:svc],
120
+ 'params' => parameters[:params],
121
+ 'sid' => parameters[:sid]
122
+ )
123
+
124
+ begin
125
+ response = Net::HTTP.start(uri.hostname, uri.port, { use_ssl: uri.scheme == 'https' }) do |http|
126
+ http.request(request)
127
+ end
128
+ rescue Exception => e
129
+ raise SdkException.new("Internal error: #{e}")
130
+ end
131
+
132
+ begin
133
+ response = JSON.parse(response.body)
134
+ rescue Exception => e
135
+ raise SdkException.new("Internal error: #{e}")
136
+ end
137
+
138
+ if response.class == Hash
139
+ if !response['error'].nil?
140
+ if response['error'] != 0
141
+ raise Wialon::Error.new(response['error'].to_i, (response['reason'].nil? ? '' : response['reason']))
142
+ end
143
+ end
144
+ end
145
+
146
+ return response
147
+ end
171
148
 
172
- # Unknonwn methods handler
173
- def method_missing(name, *args)
174
- if self.debug
175
- puts "Query method: #{name}"
176
- end
149
+ def debug_printer(message)
150
+ puts "*******" * 10
151
+ puts "#{message}"
152
+ puts "*******" * 10
153
+ end
177
154
 
178
- return self.call(name, ((args.count === 0) ? '{}' : args[0]))
155
+ def method_missing(method_name, *args)
156
+ return self.call(method_name, args.count == 0 ? {} : args[0])
157
+ end
179
158
  end
180
159
 
181
- private
182
- def parse_errors(code)
183
- errors = {
184
- '1' => "Invalid session",
185
- '2' => "Invalid service name",
186
- '3' => "Invalid result",
187
- '4' => "Invalid input",
188
- '5' => "Error performing request",
189
- '6' => "Unknown error",
190
- '7' => "Access denied",
191
- '8' => "Invalid user name or password",
192
- '9' => "Authorization server is unavailable",
193
- '10' => "Reached limit of concurrent requests",
194
- '11' => "Password reset error",
195
- '14' => "Billing error",
196
- '1001' => "No messages for selected interval",
197
- '1002' => "Item with such unique property already exists or Item cannot be created according to billing restrictions",
198
- '1003' => "Only one request is allowed at the moment",
199
- '1004' => "Limit of messages has been exceeded",
200
- '1005' => "Execution time has exceeded the limit",
201
- '1006' => "Exceeding the limit of attempts to enter a two-factor authorization code",
202
- '1011' => "Your IP has changed or session has expired",
203
- '2014' => "Selected user is a creator for some system objects, thus this user cannot be bound to a new account",
204
- '2015' => "Sensor deleting is forbidden because of using in another sensor or advanced properties of the unit"
160
+ class Error < Exception
161
+ def initialize(code, details = '')
162
+ _errors = {
163
+ -1 => 'Unhandled error code',
164
+ 1 => 'Invalid session',
165
+ 2 => 'Invalid service name',
166
+ 3 => 'Invalid result',
167
+ 4 => 'Invalid input',
168
+ 5 => 'Error performing request',
169
+ 6 => 'Unknown error',
170
+ 7 => 'Access denied',
171
+ 8 => 'Invalid user name or password',
172
+ 9 => 'Authorization server is unavailable',
173
+ 10 => 'Reached limit of concurrent requests',
174
+ 11 => 'Password reset error',
175
+ 14 => 'Billing error',
176
+ 1001 => 'No messages for selected interval',
177
+ 1002 => 'Item with such unique property already exists or Item cannot be created according to billing restrictions',
178
+ 1003 => 'Only one request is allowed at the moment',
179
+ 1004 => 'Limit of messages has been exceeded',
180
+ 1005 => 'Execution time has exceeded the limit',
181
+ 1006 => 'Exceeding the limit of attempts to enter a two-factor authorization code',
182
+ 1011 => 'Your IP has changed or session has expired',
183
+ 2014 => 'Selected user is a creator for some system objects, thus this user cannot be bound to a new account',
184
+ 2015 => 'Sensor deleting is forbidden because of using in another sensor or advanced properties of the unit'
205
185
  }
206
186
 
207
- if errors[code.to_s].nil?
208
- return "Unknown error"
187
+ @message = ''
188
+ if _errors[code].nil?
189
+ @message = "#{_errors[-1]}"
209
190
  else
210
- return errors[code.to_s]
191
+ @message = "#{_errors[code]}"
211
192
  end
212
- end
213
- # SID setter
214
- def set_sid(sid)
215
- self.sid = sid
216
- end
217
193
 
218
- # SID getter
219
- def get_sid
220
- return self.sid
221
- end
194
+ if details.length > 0
195
+ @message += " - #{details}"
196
+ end
222
197
 
223
- # Update extra parameters
224
- def update_extra_params(params)
225
- self.default_params.replace(params)
198
+ @code = code
199
+ super("WialonError(code: #{@code}, reason: #{@message})")
226
200
  end
201
+ end
202
+ end
203
+
204
+ class SdkException < Exception
205
+ def initialize(message = '')
206
+ @message = message
207
+ super("SdkException(#{@message})")
208
+ end
227
209
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: wialon
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.2.1
4
+ version: 2.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Golden M Software