Browse code

bug fix 20151227

Jeff Owrey authored on 12/28/2015 02:58:35
Showing 4 changed files
... ...
@@ -32,7 +32,7 @@ import subprocess
32 32
 
33 33
     ### DEFINE FILE LOCATIONS ###
34 34
 
35
-_RRD_FILE = "/home/pi/database/radmonData.rrd"  # the file that stores the data
35
+_RRD_FILE = "/home/{user}/database/radmonData.rrd"  # the file that stores the data
36 36
 _RRD_SIZE_IN_DAYS = 370 # days
37 37
 _DATABASE_UPDATE_INTERVAL = 30
38 38
 
... ...
@@ -40,19 +40,23 @@ import os
40 40
 import json
41 41
 import multiprocessing
42 42
 
43
-## Define constants
44
-_TMP_DIRECTORY = "/tmp/radmon"
45
-_RRD_FILE = "/home/pi/database/radmonData.rrd"  # the file that stores the data
46
-_OUTPUT_DATA_FILE = "/tmp/radmon/radmonData.js"
47
-
48
-_WEB_DATA_UPDATE_INTERVAL = 1
49
-_CHART_UPDATE_INTERVAL = 60
50
-_DATABASE_UPDATE_INTERVAL = 30
43
+    ### FILE AND FOLDER LOCATIONS ###
44
+
45
+_TMP_DIRECTORY = "/tmp/radmon" # folder for charts and output data file
46
+_RRD_FILE = "/home/{user}/database/radmonData.rrd"  # database that stores the data
47
+_OUTPUT_DATA_FILE = "/tmp/radmon/radmonData.js" # output file used by HTML docs
48
+
49
+    ### GLOBAL CONSTANTS ###
50
+
51
+_DEFAULT_WEB_DATA_UPDATE_INTERVAL = 10
52
+_CHART_UPDATE_INTERVAL = 60 # defines how often the charts get updated
53
+_DATABASE_UPDATE_INTERVAL = 30 # defines how often the database gets updated
51 54
 _HTTP_REQUEST_TIMEOUT = 5 # number seconds to wait for a response to HTTP request
52 55
 
53
-## Define run time options
54
-deviceQueryInterval = 5.0  # period defines how often the RR database gets updated
55
-deviceUrl = "http://{IP address}:{port}/jsdata"  # radiation monitor network address
56
+   ### GLOBAL VARIABLES ###
57
+
58
+webUpdateInterval = _DEFAULT_WEB_DATA_UPDATE_INTERVAL  # web update frequency
59
+deviceUrl = "http://192.168.1.8"  # radiation monitor network address
56 60
 debugOption = False
57 61
 
58 62
   ###  PRIVATE METHODS  ###
... ...
@@ -66,23 +70,24 @@ def getTimeStamp():
66 70
     return time.strftime( "%Y/%m/%d %T", time.localtime() )
67 71
 ##end def
68 72
 
69
-def sendOffLineStatusMsg():
73
+def sendOffLineStatusMessage():
70 74
     """Sets the status of the the upstream device to "offline" and sends
71 75
        blank data to the downstream clients.
72 76
        Parameters: none
73 77
        Returns nothing.
74 78
     """
75
-    sTmp = "\"time\":\"\",\"CPS\":\"\",\"CPM\":\"\"," \
79
+    sTmp = "\"date\":\"\",\"CPS\":\"\",\"CPM\":\"\"," \
76 80
            "\"uSvPerHr\":\"\",\"Mode\":\"\",\"status\":\"offline\""
77 81
 
78 82
     lsTmp = sTmp.split(',')
79
-    writeJSONfile(lsTmp)
83
+    lsTmp[0] = "\"date\":\"%s\"" % getTimeStamp()
84
+    writeOutputDataFile(lsTmp)
80 85
     return
81 86
 ##end def
82 87
 
83 88
   ###  PUBLIC METHODS  ###
84 89
 
85
-def getDataString(deviceUrl, HttpRequestTimeout):
90
+def getRadmonData(deviceUrl, HttpRequestTimeout):
86 91
         """Send http request to radiation monitoring device.  The response
87 92
            from the device contains the radiation data.  The data is formatted
88 93
            as an html document.
... ...
@@ -95,14 +100,13 @@ def getDataString(deviceUrl, HttpRequestTimeout):
95 100
         """
96 101
         content = ""
97 102
         try:
98
-            conn = urllib2.urlopen(deviceUrl, timeout=HttpRequestTimeout)
103
+            conn = urllib2.urlopen(deviceUrl + "/jsdata", timeout=HttpRequestTimeout)
99 104
         except Exception, exError:
100 105
             # If no response is received from the device, then assume that
101 106
             # the device is down or unavailable over the network.  In
102 107
             # that case set the status of the device to offline.
103 108
             print "%s: device offline: %s" % \
104 109
                                 (getTimeStamp(), exError)
105
-            sendOffLineStatusMsg()
106 110
             return None
107 111
         else:
108 112
             for line in conn:
... ...
@@ -112,9 +116,6 @@ def getDataString(deviceUrl, HttpRequestTimeout):
112 116
                     (getTimeStamp())
113 117
                 return None
114 118
             del conn
115
-            
116
-            if debugOption:
117
-                print "%s\n" % content # DEBUG
118 119
             return content
119 120
 ##end def
120 121
 
... ...
@@ -148,9 +149,6 @@ def parseDataString(sData, lsData, dData):
148 149
         if "=" in item:
149 150
             dData[item.split('=')[0]] = item.split('=')[1]
150 151
 
151
-    if debugOption and 0:
152
-        print lsData
153
-        print dData
154 152
     return True
155 153
 ##end def
156 154
 
... ...
@@ -186,7 +184,7 @@ def convertData(lsData, dData):
186 184
     return result
187 185
 ##end def
188 186
 
189
-def writeJSONfile(lsData):
187
+def writeOutputDataFile(lsData):
190 188
     """Convert individual weather string data items as necessary.
191 189
        Parameters:
192 190
            lsData - a list object containing the data to be written
... ...
@@ -198,16 +196,17 @@ def writeJSONfile(lsData):
198 196
 
199 197
     # Apply JSON formatting to the string and write it to a
200 198
     # file for use by html documents.
201
-    strJSON = "[{%s}]\n" % (sTmp)
199
+    sData = "[{%s}]\n" % (sTmp)
202 200
 
203 201
     try:
204 202
         fc = open(_OUTPUT_DATA_FILE, "w")
205
-        fc.write(strJSON)
203
+        fc.write(sData)
206 204
         fc.close()
207 205
     except Exception, exError:
208 206
         print "%s: write to JSON file failed: %s" % \
209 207
                              (getTimeStamp(), exError)
210 208
         return False
209
+
211 210
     return True
212 211
 ## end def
213 212
 
... ...
@@ -284,7 +283,7 @@ def getCLarguments():
284 283
           -u sets the url of the radiation monitoring device
285 284
        Returns nothing.
286 285
     """
287
-    global debugOption, deviceQueryInterval, deviceURL
286
+    global debugOption, webUpdateInterval, deviceUrl
288 287
 
289 288
     index = 1
290 289
     while index < len(sys.argv):
... ...
@@ -292,13 +291,13 @@ def getCLarguments():
292 291
             debugOption = True
293 292
         elif sys.argv[index] == '-t':
294 293
             try:
295
-                deviceQueryInterval = abs(int(sys.argv[index + 1]))
294
+                webUpdateInterval = abs(int(sys.argv[index + 1]))
296 295
             except:
297 296
                 print "invalid polling period"
298 297
                 exit(-1)
299 298
             index += 1
300 299
         elif sys.argv[index] == '-u':
301
-            deviceURL = sys.argv[index + 1]
300
+            deviceUrl = sys.argv[index + 1]
302 301
             index += 1
303 302
         else:
304 303
             cmd_name = sys.argv[0].split('/')
... ...
@@ -326,10 +325,10 @@ def main():
326 325
        Parameters: none
327 326
        Returns nothing.
328 327
     """
328
+
329 329
     lastChartUpdateTime = - 1 # last time charts generated
330 330
     lastDatabaseUpdateTime = -1 # last time the rrdtool database updated
331 331
     lastWebDataUpdateTime = -1 # last time output JSON file updated
332
-    lastDeviceQueryTime = -1 # last time radiation device queried for data
333 332
     dData = {}  # dictionary object for temporary data storage
334 333
     lsData = [] # list object for temporary data storage
335 334
 
... ...
@@ -352,13 +351,14 @@ def main():
352 351
 
353 352
         # At the radiation device query interval request and process
354 353
         # the data from the device.
355
-        if currentTime - lastDeviceQueryTime > deviceQueryInterval:
356
-            lastDeviceQueryTime = currentTime
354
+        if currentTime - lastWebDataUpdateTime > webUpdateInterval:
355
+            llastWebDataUpdateTime = currentTime
357 356
             result = True
358 357
 
359 358
             # Get the data string from the device.
360
-            sData = getDataString(deviceUrl, _HTTP_REQUEST_TIMEOUT)
359
+            sData = getRadmonData(deviceUrl, _HTTP_REQUEST_TIMEOUT)
361 360
             if sData == None:
361
+                sendOffLineStatusMessage()
362 362
                 result = False
363 363
 
364 364
             # If successful parse the data.
... ...
@@ -368,19 +368,16 @@ def main():
368 368
             # If parsing successful, convert the data.
369 369
             if result:
370 370
                 result = convertData(lsData, dData)
371
-                
372
-        # At the web update interval, update the JSON file used to pass
373
-        # radiation data to html documents.
374
-        if currentTime - lastWebDataUpdateTime > _WEB_DATA_UPDATE_INTERVAL:
375
-            lastWebDataUpdateTime = currentTime
371
+
372
+            # If conversion successful, write data to output file.
376 373
             if result:
377
-                lsData[0] = "\"time\":\"%s\"" % getTimeStamp()
378
-                writeJSONfile(lsData)
374
+                lsData[0] = "\"date\":\"%s\"" % getTimeStamp()
375
+                writeOutputDataFile(lsData)
379 376
 
380 377
         # At the rrdtool database update interval, update the database.
381 378
         if currentTime - lastDatabaseUpdateTime > _DATABASE_UPDATE_INTERVAL:   
379
+            lastDatabaseUpdateTime = currentTime
382 380
             if result:
383
-                lastDatabaseUpdateTime = currentTime
384 381
                 ## Update the round robin database with the parsed data.
385 382
                 result = updateDatabase(dData)
386 383
 
... ...
@@ -395,8 +392,8 @@ def main():
395 392
 
396 393
         elapsedTime = time.time() - currentTime
397 394
         if debugOption:
398
-            print "processing time: %s\n" % elapsedTime
399
-        remainingTime = _WEB_DATA_UPDATE_INTERVAL - elapsedTime
395
+            print "web update: %6f sec\n" % elapsedTime
396
+        remainingTime = webUpdateInterval - elapsedTime
400 397
         if remainingTime > 0:
401 398
             time.sleep(remainingTime)
402 399
              
... ...
@@ -1,15 +1,16 @@
1 1
 #!/bin/bash
2 2
 #
3
-APP_PATH="/home/pi/bin/"
4
-LOG_PATH=/tmp/log
5
-
6
-cd $APP_PATH
7
-
8
-# First start up RR database update app
3
+APP_PATH="/home/{user}/bin"
4
+LOG_PATH="/home/{user}/log"
9 5
 
10 6
 PROCESS_ID="$(ps x | awk '/[r]admonAgent.py/{print $1}')"
7
+
11 8
 if [ -n "$PROCESS_ID" ]; then
12
-  printf "radmon agent running [%s]\n" $PROCESS_ID
9
+  if [ "$1" != "-q" ]; then
10
+    printf "radmon agent running [%s]\n" $PROCESS_ID
11
+  fi
13 12
 else
14
-  ./radmonAgent.py -t 5 -u 'http://73.157.139.23:4371' >> $LOG_PATH/radmonAgent.log 2>&1 &
13
+  printf "starting up radmon agent\n"
14
+  cd $APP_PATH
15
+  ./radmonAgent.py -t 10 -u 'http://73.157.139.23:4371/jsdata' >> $LOG_PATH/radmonAgent.log 2>&1 &
15 16
 fi
... ...
@@ -166,18 +166,19 @@
166 166
       var timeStamp
167 167
       var date;
168 168
       var time;
169
-      var sTmp;
169
+      var hourminute;
170 170
 
171
-      timeStamp = dataItem.time;
172
-      if (timeStamp != "") {
171
+      timeStamp = dataItem.date;
172
+      if (timeStamp != "") { 
173 173
         date = timeStamp.split(" ")[0];
174 174
         time = timeStamp.split(" ")[1];
175
+        hourminute = time.split(":")[0] + ":" + time.split(":")[1];
175 176
         $("#date").text(date);
176
-        $("#time").text(time);
177
+        $("#time").text(hourminute + " (PDT)");
177 178
       } else {
178 179
         $("#date").text("");
179 180
         $("#time").text("");
180
-      }        
181
+      }
181 182
       
182 183
       $("#cps").text(dataItem.CPS);
183 184
       $("#cpm").text(dataItem.CPM);
... ...
@@ -198,7 +199,7 @@
198 199
     $(document).ready(function() {
199 200
       getRadmon();
200 201
       getGraphs();
201
-      setInterval(getRadmon, 1000);
202
+      setInterval(getRadmon, 10000);
202 203
       setInterval(getGraphs, 60000);
203 204
     });
204 205