Created
July 20, 2017 09:29
-
-
Save auxiliary-character/66f2cfa378dac1a410745ca6b0de5c29 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.*; | |
import java.util.concurrent.locks.ReentrantReadWriteLock; | |
import java.util.concurrent.locks.ReadWriteLock; | |
import java.util.regex.*; | |
import java.util.HashMap; | |
import java.util.Scanner; | |
import java.util.Timer; | |
import java.util.TimerTask; | |
public class RoboSight{ | |
protected String m_url; | |
private Timer m_timer; | |
private HashMap<String, Float> m_hashmap; | |
private ReadWriteLock m_lock; | |
public RoboSight(){ | |
this("http://10.40.9.13/data.html"); | |
} | |
public RoboSight(String url){ | |
m_url = url; | |
m_timer = new Timer(); | |
m_hashmap = new HashMap<String, Float>(); | |
m_lock = new ReentrantReadWriteLock(); | |
} | |
private class RoboSightTask extends TimerTask{ | |
private RoboSight m_roboSight; | |
public RoboSightTask(RoboSight roboSight){ | |
m_roboSight = roboSight; | |
} | |
@Override | |
public void run(){ | |
String payloadString = httpRequest(m_url); | |
parse(payloadString); | |
} | |
} | |
public void start() { | |
RoboSightTask task = new RoboSightTask(this); | |
m_timer.schedule(task, 0L, 100L); | |
} | |
public float get(String key){ | |
m_lock.readLock().lock(); | |
try{ | |
if(m_hashmap.containsKey(key)){ | |
return m_hashmap.get(key); | |
} | |
else{ | |
return 0.0f; | |
} | |
} | |
finally{ | |
m_lock.readLock().unlock(); | |
} | |
} | |
private void clear(){ | |
m_hashmap.clear(); | |
} | |
protected void parse(String input){ | |
Pattern dataRegex = Pattern.compile("(\\w+) = ([\\d\\.\\-]+)"); | |
Matcher matcher = dataRegex.matcher(input); | |
m_lock.writeLock().lock(); | |
try{ | |
clear(); | |
while(matcher.find()){ | |
m_hashmap.put(matcher.group(1), Float.parseFloat(matcher.group(2))); | |
} | |
} | |
finally{ | |
m_lock.writeLock().unlock(); | |
} | |
} | |
protected static String httpRequest(String url){ | |
String output = ""; | |
try{ | |
InputStream stream = new URL(url).openStream(); | |
BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); | |
StringBuilder response = new StringBuilder(); | |
String line; | |
while((line = reader.readLine()) != null){ | |
response.append(line); | |
response.append("\n"); | |
} | |
reader.close(); | |
output = response.toString(); | |
} | |
catch (Exception e){ | |
e.printStackTrace(); | |
} | |
return output; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment