Guest User

Untitled

a guest
Jan 11th, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 28.77 KB | None | 0 0
  1. package com.example.jessica.iair;
  2.  
  3. import android.content.Context;
  4. import android.os.AsyncTask;
  5. import android.util.Log;
  6. import android.widget.Toast;
  7.  
  8. import org.json.JSONArray;
  9. import org.json.JSONException;
  10. import org.json.JSONObject;
  11.  
  12. import java.io.BufferedReader;
  13. import java.io.DataOutputStream;
  14. import java.io.IOException;
  15. import java.io.InputStream;
  16. import java.io.InputStreamReader;
  17. import java.lang.ref.WeakReference;
  18. import javax.net.ssl.HttpsURLConnection;
  19.  
  20. import java.net.HttpURLConnection;
  21. import java.net.MalformedURLException;
  22. import java.net.URL;
  23. import java.util.ArrayList;
  24. import java.util.Arrays;
  25. import java.util.Collections;
  26. import java.util.concurrent.ExecutionException;
  27.  
  28. import static android.provider.Settings.Global.getString;
  29.  
  30. /**
  31. * Created by luisvf7 on 04/11/2017.
  32. */
  33.  
  34. public class API {
  35.  
  36. private Context myContext; //context para conseguir fazer mensagem Toast
  37. public API(Context context) {
  38. myContext= context;
  39. }
  40.  
  41. public Integer getPublicChannel(String location) throws ExecutionException, InterruptedException, JSONException {
  42. AsyncTask<String, Void, JSONArray> task = new GetPublicChannels(myContext); //instanciar async task
  43.  
  44. String url = Constants.PUBLIC_CHANNEL_URL_PORTUGAL+location.toLowerCase().replace(" ","%20"); //construção do url para api *fazer parse
  45.  
  46. JSONArray publicChannels= task.execute(url).get(); //execução da task para obter canais publicos da location
  47. Log.d("PublicChannel: "+ location, publicChannels.toString());
  48.  
  49. for (int i = 0; i < publicChannels.length(); i++) { //percorrer canais
  50. JSONObject channel = publicChannels.getJSONObject(i); //obter canal
  51. JSONArray tags = channel.getJSONArray("tags"); //obter array de tags do canal
  52. for (int j = 0; j < tags.length(); j++) { //percorrer tags
  53. JSONObject tag = tags.getJSONObject(j);//obter tag
  54. if(tag.get("name").toString().equalsIgnoreCase(location)) //verificar se coincide com string location
  55. return channel.getInt("id"); //retornar id do canal
  56. }
  57. }
  58.  
  59. return -1;
  60. }
  61.  
  62. public ArrayList<FeedInfoAirQuality> getAllAirQualityValues(String location, String params) throws JSONException {
  63. String channelID;
  64. String apiKey;
  65. ArrayList<FeedInfoAirQuality> feedsReturnList = new ArrayList<>();
  66.  
  67. JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
  68.  
  69. if (cidadeJson == null)
  70. return null;
  71.  
  72. try {
  73. channelID = cidadeJson.getString("qualidade-api-id");
  74. apiKey = cidadeJson.getString("qualidade-api-key");
  75. } catch (JSONException e) {
  76. e.printStackTrace();
  77. return null;
  78. }
  79.  
  80. String url = "https://api.thingspeak.com/channels/" + channelID + "/feeds.json?api_key=" + apiKey; //construção de url para obter channel
  81.  
  82. if (params != null) { //parametros opcionais existem
  83. url += "&"+params;
  84. }
  85.  
  86. FeedInfoAirQuality feedInfo = new FeedInfoAirQuality(); //instanciar feedInfoTempHum
  87.  
  88. GetChannelInfo task = new GetChannelInfo(myContext); //instanciar class GetChannelInfo
  89.  
  90. JSONObject channelJSON = null; //executar task de GetChannelInfo
  91.  
  92. try {
  93. channelJSON = task.execute(url).get();
  94. if (channelJSON == null) { //task é null se não conseguir obter informação do canal
  95. Toast.makeText(myContext, "Error ao obter informação do canal " + channelID, Toast.LENGTH_SHORT).show();
  96. return null;
  97. }
  98.  
  99. JSONObject channelMeta = channelJSON.getJSONObject("channel");
  100. ArrayList<String> fields = new ArrayList<>();
  101.  
  102. for (int i = 1; i < channelMeta.length(); i++) {
  103. //Log.d("CHANNEL FIELDS", channelMeta.getString(i));
  104. try {
  105. String field = channelMeta.getString("field" + i);
  106. if (field != null)
  107. fields.add(field);
  108. } catch (JSONException e) {
  109.  
  110. }
  111. }
  112. Log.d("FIELDS", fields.toString());
  113.  
  114. JSONArray arrayFeeds = channelJSON.getJSONArray("feeds");
  115. if (arrayFeeds.length() == 0) {
  116. return null;
  117. }
  118. for (int i = 0; i < arrayFeeds.length(); i++) {
  119. JSONObject feed = arrayFeeds.getJSONObject(i);
  120. if(feed!=null)
  121. feedsReturnList.add(getFeedInfoAirQualityFromJSONObj(feed,fields));
  122. }
  123. Collections.reverse(feedsReturnList);
  124. return feedsReturnList;
  125.  
  126. } catch (InterruptedException e) {
  127. e.printStackTrace();
  128. } catch (ExecutionException e) {
  129. e.printStackTrace();
  130. } catch (JSONException e) {
  131. e.printStackTrace();
  132. }
  133.  
  134. return null;
  135. }
  136.  
  137. public ArrayList<FeedInfoTempHum> getAllSensorValues(String location, String params) {
  138. String channelID;
  139. String apiKey;
  140. ArrayList<FeedInfoTempHum> feedsReturnList = new ArrayList<>();
  141.  
  142. JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
  143.  
  144. if (cidadeJson == null)
  145. return null;
  146.  
  147. try {
  148. channelID = cidadeJson.getString("temp-hum-api-id");
  149. apiKey = cidadeJson.getString("temp-hum-api-key");
  150. } catch (JSONException e) {
  151. e.printStackTrace();
  152. return null;
  153. }
  154.  
  155. String url = "https://api.thingspeak.com/channels/" + channelID + "/feeds.json?api_key=" + apiKey; //construção de url para obter channel
  156.  
  157. if (params != null) { //parametros opcionais existem
  158. url += "&"+params;
  159. }
  160.  
  161. FeedInfoTempHum feedInfoTempHum = new FeedInfoTempHum(); //instanciar feedInfoTempHum
  162.  
  163. GetChannelInfo task = new GetChannelInfo(myContext); //instanciar class GetChannelInfo
  164.  
  165. JSONObject channelJSON = null; //executar task de GetChannelInfo
  166.  
  167. try {
  168. channelJSON = task.execute(url).get();
  169. if (channelJSON == null) { //task é null se não conseguir obter informação do canal
  170. Toast.makeText(myContext, "Error ao obter informação do canal " + channelID, Toast.LENGTH_SHORT).show();
  171. return null;
  172. }
  173.  
  174. JSONObject channelMeta = channelJSON.getJSONObject("channel");
  175. ArrayList<String> fields = new ArrayList<>();
  176.  
  177. for (int i = 1; i < channelMeta.length(); i++) {
  178. //Log.d("CHANNEL FIELDS", channelMeta.getString(i));
  179. try {
  180. String field = channelMeta.getString("field" + i);
  181. if (field != null)
  182. fields.add(field);
  183. } catch (JSONException e) {
  184.  
  185. }
  186. }
  187. Log.d("FIELDS", fields.toString());
  188.  
  189. JSONArray arrayFeeds = channelJSON.getJSONArray("feeds");
  190.  
  191. if (arrayFeeds.length() == 0) {
  192. return null;
  193. }
  194.  
  195. for (int i = 0; i < arrayFeeds.length(); i++) {
  196. JSONObject feed = arrayFeeds.getJSONObject(i);
  197. if(feed!=null)
  198. feedsReturnList.add(getFeedInfoTempHumFromJSONObj(feed,fields));
  199. }
  200.  
  201. Collections.reverse(feedsReturnList);
  202. return feedsReturnList;
  203.  
  204. } catch (InterruptedException e) {
  205. e.printStackTrace();
  206. } catch (ExecutionException e) {
  207. e.printStackTrace();
  208. } catch (JSONException e) {
  209. e.printStackTrace();
  210. }
  211.  
  212. return null;
  213. }
  214.  
  215. public FeedInfoTempHum getLastFeedInfoTempHumCity(String location, String params) throws ExecutionException, InterruptedException, JSONException {
  216.  
  217. JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
  218.  
  219. if(cidadeJson == null)
  220. return null;
  221.  
  222. String channelID = cidadeJson.getString("temp-hum-api-id");
  223. String apiKey = cidadeJson.getString("temp-hum-api-key");
  224.  
  225. String url = "https://api.thingspeak.com/channels/"+channelID+"/feeds.json?api_key="+apiKey; //construção de url para obter channel
  226.  
  227. if(params!=null){ //parametros opcionais existem
  228. url+="?"+params;
  229. }
  230.  
  231. FeedInfoTempHum feedInfoTempHum = new FeedInfoTempHum(); //instanciar feedInfoTempHum
  232.  
  233. GetChannelInfo task = new GetChannelInfo(myContext); //instanciar class GetChannelInfo
  234.  
  235. JSONObject channelJSON = task.execute(url).get(); //executar task de GetChannelInfo
  236.  
  237. if(channelJSON == null){ //task é null se não conseguir obter informação do canal
  238. Toast.makeText(myContext,"Error ao obter informação do canal "+channelID,Toast.LENGTH_SHORT).show();
  239. return null;
  240. }
  241.  
  242. JSONObject channelMeta = channelJSON.getJSONObject("channel");
  243. ArrayList<String> fields = new ArrayList<>();
  244.  
  245. for (int i = 1; i < channelMeta.length(); i++) {
  246. //Log.d("CHANNEL FIELDS", channelMeta.getString(i));
  247. try {
  248. String field = channelMeta.getString("field"+i);
  249. if(field!=null)
  250. fields.add(field);
  251. }catch (JSONException e){
  252.  
  253. }
  254. }
  255. Log.d("FIELDS", fields.toString());
  256. JSONArray arrayFeeds = channelJSON.getJSONArray("feeds");
  257. if (arrayFeeds.length() == 0) {
  258. return null;
  259. }
  260. JSONObject lastFeedInfo = arrayFeeds.getJSONObject(arrayFeeds.length()-1); //obter o ultimo feed
  261.  
  262. Log.d("LASTFEEDINFO", lastFeedInfo.toString());
  263.  
  264. return getFeedInfoTempHumFromJSONObj(lastFeedInfo,fields);
  265. }
  266.  
  267. public FeedInfoAirQuality getLastFeedInfoAirQualityCity(String location, String params) throws ExecutionException, InterruptedException, JSONException {
  268.  
  269. JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
  270.  
  271. if(cidadeJson == null)
  272. return null;
  273.  
  274. String channelID = cidadeJson.getString("qualidade-api-id");
  275. String apiKey = cidadeJson.getString("qualidade-api-key");
  276.  
  277. String url = "https://api.thingspeak.com/channels/"+channelID+"/feeds.json?api_key="+apiKey; //construção de url para obter channel
  278.  
  279. if(params!=null){ //parametros opcionais existem
  280. url+="?"+params;
  281. }
  282.  
  283. FeedInfoAirQuality feedInfoQualidadeAr = new FeedInfoAirQuality(); //instanciar feedInfoTempHum
  284.  
  285. GetChannelInfo task = new GetChannelInfo(myContext); //instanciar class GetChannelInfo
  286.  
  287. JSONObject channelJSON = task.execute(url).get(); //executar task de GetChannelInfo
  288.  
  289. if(channelJSON == null){ //task é null se não conseguir obter informação do canal
  290. Toast.makeText(myContext,"Error ao obter informação do canal "+channelID,Toast.LENGTH_SHORT).show();
  291. return null;
  292. }
  293.  
  294. JSONObject channelMeta = channelJSON.getJSONObject("channel");
  295. ArrayList<String> fields = new ArrayList<>();
  296.  
  297. for (int i = 1; i < channelMeta.length(); i++) {
  298. //Log.d("CHANNEL FIELDS", channelMeta.getString(i));
  299. try {
  300. String field = channelMeta.getString("field"+i);
  301. if(field!=null)
  302. fields.add(field);
  303. }catch (JSONException e){
  304.  
  305. }
  306. }
  307. Log.d("FIELDS", fields.toString());
  308. JSONArray arrayFeeds = channelJSON.getJSONArray("feeds");
  309. if (arrayFeeds.length() == 0) {
  310. return null;
  311. }
  312. JSONObject lastFeedInfo = arrayFeeds.getJSONObject(arrayFeeds.length()-1); //obter o ultimo feed
  313.  
  314. Log.d("LASTFEEDINFO", lastFeedInfo.toString());
  315.  
  316.  
  317. feedInfoQualidadeAr.setFeedInfoDate(lastFeedInfo.getString(Constants.LAST_UPDATED));
  318. feedInfoQualidadeAr.setCo(-1);
  319. feedInfoQualidadeAr.setNo2(-1);
  320. feedInfoQualidadeAr.setO3(-1);
  321.  
  322. for (int i = 1; i <= fields.size(); i++) {
  323. Log.d("FEEDINFO", "getLastFeedInfoIteration: "+i);
  324.  
  325. if (lastFeedInfo.getString("field"+i) != "null" && !lastFeedInfo.getString("field"+i).isEmpty()) {
  326.  
  327. if (Arrays.asList(Constants.O3).contains(fields.get(i - 1).toLowerCase())) { //se for field de humidade
  328. feedInfoQualidadeAr.setO3(Float.parseFloat(lastFeedInfo.getString("field" + i)));
  329. }
  330. if (Arrays.asList(Constants.NO2).contains(fields.get(i - 1).toLowerCase())) { //se for field de humidade
  331. feedInfoQualidadeAr.setNo2(Float.parseFloat(lastFeedInfo.getString("field" + i)));
  332. }
  333. if (Arrays.asList(Constants.CO).contains(fields.get(i - 1).toLowerCase())) { //se for field de humidade
  334. feedInfoQualidadeAr.setCo(Float.parseFloat(lastFeedInfo.getString("field" + i)));
  335. }
  336. }
  337. }
  338. return feedInfoQualidadeAr;
  339. }
  340.  
  341. public int postInfoEventoParaCidade(String location, CityEvent evt ) throws ExecutionException, InterruptedException {
  342.  
  343. //Buscar API KEY para POST
  344. JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
  345. String api;
  346. if(cidadeJson == null)
  347. return -1;
  348.  
  349. try {
  350. api = cidadeJson.getString("write-api-key");
  351. } catch (JSONException e) {
  352. e.printStackTrace();
  353. return -1;
  354. }
  355.  
  356. //Construir body json do evento
  357. String json;
  358. JSONObject jsonObject = new JSONObject();
  359.  
  360. try {
  361. jsonObject.accumulate("field1", evt.getAutor());
  362. jsonObject.accumulate("field2", evt.getAssunto());
  363. jsonObject.accumulate("field3", evt.getMensagem());
  364. jsonObject.accumulate("field4", evt.getUltima_localizacao());
  365. } catch (JSONException e) {
  366. e.printStackTrace();
  367. }
  368. json = jsonObject.toString();
  369. PostChannelInfo pChannelInfo = new PostChannelInfo(myContext);
  370. Log.d("UPLOAD", "postInfoEventoParaCidade: "+evt.toString());
  371. return pChannelInfo.execute(api,json).get();
  372. }
  373.  
  374. public int postInfoMedicaoSensoresParaCidade(String location, String autor, FeedInfoTempHum feed ) throws ExecutionException, InterruptedException {
  375.  
  376. //Buscar API KEY para POST
  377. JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
  378. String api;
  379. if(cidadeJson == null)
  380. return -1;
  381.  
  382. try {
  383. api = cidadeJson.getString("write-api-key-temphum");
  384. } catch (JSONException e) {
  385. e.printStackTrace();
  386. return -1;
  387. }
  388.  
  389. //Construir body json do evento
  390. String json;
  391. JSONObject jsonObject = new JSONObject();
  392.  
  393. try {
  394. //field1 - autor
  395. //field2 - humidade
  396. //field3 - temperatura
  397. jsonObject.accumulate("field1", autor);
  398. if(feed.getHumidity() != 0.0f){
  399. jsonObject.accumulate("field2", feed.getHumidity());
  400. }
  401. if(feed.getTemperature() != 0.0f){
  402. jsonObject.accumulate("field3", feed.getTemperature());
  403. }
  404.  
  405. } catch (JSONException e) {
  406. e.printStackTrace();
  407. }
  408. json = jsonObject.toString();
  409. PostChannelInfo pChannelInfo = new PostChannelInfo(myContext);
  410. Log.d("UPLOAD", "postInfoMedicaoSensoresParaCidade: "+feed.toString());
  411. return pChannelInfo.execute(api,json).get();
  412. }
  413.  
  414. public ArrayList<CityEvent> getEventsCity(String location, String params) throws ExecutionException, InterruptedException, JSONException {
  415. Toast.makeText(myContext, "A carregar eventos..", Toast.LENGTH_SHORT).show();
  416. JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
  417. ArrayList<CityEvent> events = new ArrayList<>();
  418.  
  419. if(cidadeJson == null)
  420. return null;
  421.  
  422. String channelID = cidadeJson.getString("events-api-id");
  423. String apiKey = cidadeJson.getString("events-api-key");
  424.  
  425. String url = "https://api.thingspeak.com/channels/"+channelID+"/feeds.json?api_key="+apiKey; //construção de url para obter channel
  426.  
  427. if(params!=null){ //parametros opcionais existem
  428. url+="?"+params;
  429. }
  430.  
  431. GetChannelInfo task = new GetChannelInfo(myContext); //instanciar class GetChannelInfo
  432.  
  433. JSONObject channelJSON = task.execute(url).get(); //executar task de GetChannelInfo
  434.  
  435. if(channelJSON == null){ //task é null se não conseguir obter informação do canal
  436. Toast.makeText(myContext,"Error ao obter informação do canal "+channelID,Toast.LENGTH_SHORT).show();
  437. return null;
  438. }
  439.  
  440. JSONObject channelMeta = channelJSON.getJSONObject("channel");
  441. ArrayList<String> fields = new ArrayList<>();
  442.  
  443. for (int i = 1; i < channelMeta.length(); i++) {
  444. //Log.d("CHANNEL FIELDS", channelMeta.getString(i));
  445. try {
  446. String field = channelMeta.getString("field"+i);
  447. if(field!=null)
  448. fields.add(field);
  449. }catch (JSONException e){
  450.  
  451. }
  452. }
  453. Log.d("FIELDS", fields.toString());
  454. JSONArray arrayFeeds = channelJSON.getJSONArray("feeds");
  455. if (arrayFeeds.length() == 0) {
  456. return null;
  457. }
  458.  
  459. for (int i = 0; i<=arrayFeeds.length()-1;i++){ //iterar todos os os objects
  460. CityEvent ctEvent = new CityEvent(null,null,null,null);
  461. JSONObject eventJson = arrayFeeds.getJSONObject(i);
  462. ctEvent.setData(eventJson.getString("created_at"));
  463.  
  464. for (int j = 1; j <= fields.size(); j++) { //iterar todos os fields
  465. Log.d("FEEDINFO", "getLastFeedInfoIteration: "+i);
  466. if (eventJson.getString("field"+j) != "null" && !eventJson.getString("field"+j).isEmpty()) {
  467. if ( fields.get(j-1).equalsIgnoreCase("autor")) {
  468. ctEvent.setAutor(eventJson.getString("field"+j));
  469. }
  470. if ( fields.get(j-1).equalsIgnoreCase("assunto")) {
  471. ctEvent.setAssunto(eventJson.getString("field"+j));
  472. }
  473. if ( fields.get(j-1).equalsIgnoreCase("mensagem")) {
  474. ctEvent.setMensagem(eventJson.getString("field"+j));
  475. }
  476. if ( fields.get(j-1).equalsIgnoreCase("ultima_localizacao")) {
  477. ctEvent.setUltima_localizacao(eventJson.getString("field"+j));
  478. }
  479. }
  480. }
  481. events.add(ctEvent);
  482. }
  483.  
  484. return events;
  485. }
  486.  
  487. private static class GetPublicChannels extends AsyncTask<String, Void, JSONArray> {
  488.  
  489. private WeakReference<Context> activityReference;
  490.  
  491. GetPublicChannels(Context context) {
  492. activityReference = new WeakReference<>(context);
  493. }
  494.  
  495. @Override
  496. protected void onPreExecute() {
  497. //Toast.makeText(activityReference.get(), "Getting Info", Toast.LENGTH_SHORT).show();
  498. }
  499.  
  500. @Override
  501. protected JSONArray doInBackground(String... params) {
  502.  
  503. HttpURLConnection connection = null;
  504. BufferedReader reader = null;
  505.  
  506. try {
  507. URL url = new URL(params[0].toString());
  508. connection = (HttpURLConnection) url.openConnection();
  509. connection.connect();
  510.  
  511. InputStream stream = connection.getInputStream();
  512.  
  513. reader = new BufferedReader(new InputStreamReader(stream));
  514.  
  515. StringBuffer buffer = new StringBuffer();
  516. String line = "";
  517.  
  518. while ((line = reader.readLine()) != null) {
  519. buffer.append(line+"\n");
  520. Log.d("Response: ", "> " + line);
  521.  
  522. }//final de while temos a resposta (json)
  523.  
  524. JSONObject obj = new JSONObject(buffer.toString()); //criar json object
  525.  
  526. return obj.getJSONArray("channels"); //obter array de canais
  527.  
  528.  
  529. } catch (MalformedURLException e) {
  530. e.printStackTrace();
  531. } catch (IOException | JSONException e ) {
  532. e.printStackTrace();
  533. } finally {
  534. if (connection != null) {
  535. connection.disconnect();
  536. }
  537. try {
  538. if (reader != null) {
  539. reader.close();
  540. }
  541. } catch (IOException e) {
  542. e.printStackTrace();
  543. }
  544. }
  545. return null;
  546. }
  547.  
  548. }
  549.  
  550. private static class GetChannelInfo extends AsyncTask<String, Void, JSONObject> {
  551.  
  552. private WeakReference<Context> activityReference;
  553.  
  554. GetChannelInfo(Context context) {
  555. activityReference = new WeakReference<>(context);
  556. }
  557.  
  558. @Override
  559. protected void onPreExecute() {
  560.  
  561. //Toast.makeText(activityReference.get(), "Getting Info", Toast.LENGTH_SHORT).show();
  562.  
  563. }
  564.  
  565. @Override
  566. protected JSONObject doInBackground(String... params) {
  567.  
  568. HttpURLConnection connection = null;
  569. BufferedReader reader = null;
  570.  
  571. try {
  572. URL url = new URL(params[0]);
  573. connection = (HttpURLConnection) url.openConnection();
  574. connection.connect();
  575.  
  576. InputStream stream = connection.getInputStream();
  577.  
  578. reader = new BufferedReader(new InputStreamReader(stream));
  579.  
  580. StringBuffer buffer = new StringBuffer();
  581. String line = "";
  582.  
  583. while ((line = reader.readLine()) != null) {
  584. buffer.append(line+"\n");
  585. Log.d("Response: ", "> " + line);
  586. }
  587.  
  588. return new JSONObject(buffer.toString());
  589.  
  590. } catch (MalformedURLException e) {
  591. e.printStackTrace();
  592. } catch (IOException | JSONException e ) {
  593. e.printStackTrace();
  594. } finally {
  595. if (connection != null) {
  596. connection.disconnect();
  597. }
  598. try {
  599. if (reader != null) {
  600. reader.close();
  601. }
  602. } catch (IOException e) {
  603. e.printStackTrace();
  604. }
  605. }
  606. return null;
  607. }
  608.  
  609.  
  610. }
  611.  
  612. private static class PostChannelInfo extends AsyncTask<String, Void, Integer> {
  613.  
  614. private WeakReference<Context> activityReference;
  615.  
  616. PostChannelInfo(Context context) {
  617. activityReference = new WeakReference<>(context);
  618. }
  619.  
  620. @Override
  621. protected void onPreExecute() {
  622.  
  623. //Toast.makeText(activityReference.get(), "Getting Info", Toast.LENGTH_SHORT).show();
  624.  
  625. }
  626.  
  627. @Override
  628. protected Integer doInBackground(String... params) {
  629. try {
  630. URL url = new URL("https://api.thingspeak.com/update.json"); //Enter URL here
  631. HttpsURLConnection httpURLConnection = (HttpsURLConnection)url.openConnection();
  632.  
  633. httpURLConnection.setDoOutput(true);
  634. httpURLConnection.setRequestProperty("THINGSPEAKAPIKEY",params[0]);
  635. httpURLConnection.setRequestMethod("POST"); // here you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
  636. httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
  637. httpURLConnection.connect();
  638.  
  639. DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
  640. wr.write(params[1].getBytes("UTF-8"));
  641. wr.flush();
  642. wr.close();
  643. return httpURLConnection.getResponseCode();
  644. } catch (MalformedURLException e) {
  645. e.printStackTrace();
  646. } catch (IOException e) {
  647. e.printStackTrace();
  648. }
  649.  
  650. return -1;
  651. }
  652.  
  653.  
  654. }
  655.  
  656. private FeedInfoTempHum getFeedInfoTempHumFromJSONObj(JSONObject obj, ArrayList<String> fields){
  657. FeedInfoTempHum feedInfoTempHum = new FeedInfoTempHum();
  658. try {
  659. feedInfoTempHum.setFeedInfoDate(obj.getString(Constants.LAST_UPDATED));
  660. feedInfoTempHum.setTemperature(Float.MAX_VALUE);
  661. feedInfoTempHum.setHumidity(-1);
  662.  
  663. for (int i = 1; i <= fields.size(); i++) {
  664. Log.d("FEEDINFO", "getLastFeedInfoIteration: "+i);
  665.  
  666. if (obj.getString("field"+i) != "null" && !obj.getString("field"+i).isEmpty()
  667. && !obj.getString("field"+i).equalsIgnoreCase(String.valueOf(R.string.TEMP_SENSOR_ND)) && !obj.getString("field"+i).equalsIgnoreCase(String.valueOf(R.string.HUM_SENSOR_ND))) {
  668. if (Arrays.asList(Constants.TEMPERATURE).contains(fields.get(i - 1).toLowerCase())) { //se for field de temperatura
  669. feedInfoTempHum.setTemperature(Float.parseFloat(obj.getString("field" + i)));
  670. }
  671.  
  672. if (Arrays.asList(Constants.HUMIDITY).contains(fields.get(i - 1).toLowerCase())) { //se for field de humidade
  673. feedInfoTempHum.setHumidity(Float.parseFloat(obj.getString("field" + i)));
  674. }
  675.  
  676. }
  677. }
  678. } catch (JSONException e) {
  679. e.printStackTrace();
  680. }
  681.  
  682. return feedInfoTempHum;
  683. }
  684.  
  685. private FeedInfoAirQuality getFeedInfoAirQualityFromJSONObj(JSONObject obj, ArrayList<String> fields){
  686. FeedInfoAirQuality feedInfoAirQuality = new FeedInfoAirQuality ();
  687. try {
  688. feedInfoAirQuality.setFeedInfoDate(obj.getString(Constants.LAST_UPDATED));
  689. feedInfoAirQuality.setCo(-1);
  690. feedInfoAirQuality.setNo2(-1);
  691. feedInfoAirQuality.setO3(-1);
  692.  
  693. for (int i = 1; i <= fields.size(); i++) {
  694. Log.d("FEEDINFO", "getLastFeedInfoIteration: "+i);
  695.  
  696. if (obj.getString("field"+i) != "null" && !obj.getString("field"+i).isEmpty()
  697. && !obj.getString("field"+i).equalsIgnoreCase(String.valueOf(R.string.TEMP_SENSOR_ND)) && !obj.getString("field"+i).equalsIgnoreCase(String.valueOf(R.string.HUM_SENSOR_ND))) {
  698. if (Arrays.asList(Constants.CO).contains(fields.get(i - 1).toLowerCase())) { //se for field de temperatura
  699. feedInfoAirQuality.setCo(Float.parseFloat(obj.getString("field" + i)));
  700. }
  701.  
  702. if (Arrays.asList(Constants.NO2).contains(fields.get(i - 1).toLowerCase())) { //se for field de humidade
  703. feedInfoAirQuality.setNo2(Float.parseFloat(obj.getString("field" + i)));
  704. }
  705.  
  706. if (Arrays.asList(Constants.O3).contains(fields.get(i - 1).toLowerCase())) { //se for field de humidade
  707. feedInfoAirQuality.setO3(Float.parseFloat(obj.getString("field" + i)));
  708. }
  709.  
  710. }
  711. }
  712. } catch (JSONException e) {
  713. e.printStackTrace();
  714. }
  715.  
  716. return feedInfoAirQuality;
  717. }
  718.  
  719. private JSONObject getCidadeJson(String local){
  720. try {
  721. JSONArray obj = new JSONArray(loadJSONFromAsset());
  722. for (int i = 0; i < obj.length(); i++) {
  723. JSONObject objetoJson = obj.getJSONObject(i);
  724. if(objetoJson.getString("nome_distrito").equalsIgnoreCase(local))
  725. return objetoJson;
  726. }
  727. } catch (JSONException e) {
  728. e.printStackTrace();
  729. }
  730.  
  731. return null;
  732. }
  733.  
  734. public String loadJSONFromAsset() {
  735. String json = null;
  736. try {
  737. InputStream is = myContext.getAssets().open("distritos.json");
  738. int size = is.available();
  739. byte[] buffer = new byte[size];
  740. is.read(buffer);
  741. is.close();
  742. json = new String(buffer, "UTF-8");
  743. } catch (IOException ex) {
  744. ex.printStackTrace();
  745. return null;
  746. }
  747. return json;
  748. }
  749.  
  750.  
  751.  
  752. }
Advertisement
Add Comment
Please, Sign In to add comment