Permalink
Browse files

Merge branch 'master' of https://github.com/ashawnbandy/cecs491 into …

…dsc_20121107_prelimDocumentation
  • Loading branch information...
2 parents 9814ec0 + 22247be commit e2b6351d56f594edd90309b30f0a5ea6a613b3e4 @dchap dchap committed Nov 19, 2012
Showing 409 changed files with 3,085 additions and 6,430 deletions.
View
@@ -1,3 +1,5 @@
+*.dll
+*.exe
*.~*
[Oo]bj
[Bb]in
Binary file not shown.
@@ -3,4 +3,8 @@
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
-</configuration>
+ <runtime>
+ <loadFromRemoteSources enabled="true"/>
+ </runtime>
+
+</configuration>
@@ -3,4 +3,8 @@
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
-</configuration>
+ <runtime>
+ <loadFromRemoteSources enabled="true"/>
+ </runtime>
+
+</configuration>
@@ -3,4 +3,8 @@
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
-</configuration>
+ <runtime>
+ <loadFromRemoteSources enabled="true"/>
+ </runtime>
+
+</configuration>
@@ -1,5 +1,10 @@
{
+ "log_file":"C:\\databaseErrorLog.txt",
"firmware_version":0,
+ "transmitters":{
+ "A69-9001-50":"m,3.55,2.52",
+ "A69-9023-623":"p,74.2,130",
+ },
"discovery_commands":[
"*BROADC.A#ST,QUIT",
"*BROADC.A#ST,DISCOVERY",
@@ -48,11 +53,12 @@
"bv":"BV=([0-9]+\\.[0-9]+)",
"bu":"BU=([0-9]+\\.[0-9]+)",
"i":"I=([0-9]+\\.[0-9]+)",
+ "t":"T=([0-9]+\\.[0-9]+)",
"du":"DU=([0-9]+\\.[0-9]+)",
"ru":"RU=([0-9]+\\.[0-9]+)",
"xyz":"XYZ=(-?[0-9]+\\.[0-9]+:-?[0-9]+\\.[0-9]+:-?[0-9]+\\.[0-9]+)",
"state":":-?[0-9]+\\.[0-9]+,([A-Z]+)",
- "rtm_mode":"(OFF|232|485)",
+ "rtm_mode":",(OFF|232|485),",
"si":"SI=(POLL|[0-9]+)",
"bl":"BL=(U|[0-9]+)",
"bi":"BI=(WFS|[0-9]+)",
@@ -71,17 +77,16 @@
},
"rtm_info_response": {
"format":"(OFF|232|485),SI=(POLL|[0-9]+),BL=(U|[0-9]+),BI=(WFS|[0-9]+),MA=(U|[0-9]+),FMT=([A-Z_ ])*",
- "word_order":["rtm_mode","si","bl","bi","ma","fmt"]
+ "word_order":["receivers_id","p","decimal_sum","byte_count","rtm_mode","si","bl","bi","ma","fmt"]
},
"info_response": {
"format":"([0-9A-Z]+-[0-9A-Z]+):([0-9]{6}),'([0-9A-Z]*)',([A-Z0-9]+-[0-9]+)",
"word_order":["receiver_model","receivers_id","study_name","map","code_space","firmware_version","hardware_version"]
},
- STS,DC=([0-9]+),PC=([0-9]+)
"status_response": {
"format":"STS,DC=([0-9]+),PC=([0-9]+)",
- "word_order":["dc","pc","lv","bc","bu","i","t","du","ru","xyz"]
+ "word_order":["receivers_id","date","time","dc","pc","lv","bv","bu","i","t","du","ru","xyz"]
}
}
}
-}
+}
@@ -10,8 +10,8 @@ namespace ConsoleLogger
{
public class ConsoleLogger : Module
{
-
-
+ public ConsoleLogger(Dispatcher dispatcher)
+ : base(dispatcher) { }
public override void onRealTimeEvent(RealTimeEvent rte)
{
@@ -24,7 +24,7 @@
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
- <OutputPath>bin\Release\</OutputPath>
+ <OutputPath>..\..\ConsoleServerRunner\ConsoleServerRunner\bin\Release\modules\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -12,3 +12,5 @@ C:\Users\Derek\cecs491\Modules\ConsoleLogger\obj\Release\ConsoleLogger.pdb
C:\Users\Derek\cecs491\Modules\ConsoleLogger\bin\Release\EventSlice.dll
C:\Users\Derek\cecs491\Modules\ConsoleLogger\bin\Release\EventSlice.pdb
C:\Users\Derek\cecs491\Modules\ConsoleLogger\obj\Release\ConsoleLogger.csprojResolveAssemblyReference.cache
+\\VBOXSVR\src\cecs491\ConsoleServerRunner\ConsoleServerRunner\bin\Release\modules\ConsoleLogger.dll
+\\VBOXSVR\src\cecs491\ConsoleServerRunner\ConsoleServerRunner\bin\Release\modules\ConsoleLogger.pdb
@@ -10,73 +10,200 @@
namespace Databases
{
+ /// <summary>
+ /// This module handles the insertion of detections and status events into the database.
+ /// </summary>
public class Database : Module
{
- private string connectionString {get; set;}
+ private Dictionary<string, List<string>> sensor_calibrations { get; set; }
+ private string connectionString { get; set; }
+ private System.IO.StreamWriter logWriter { get; set; }
- public Database(Dispatcher dispatcher, string host = "localhost", string db = "csulbsha_sharktopus", string user = "testuser", string pass = "testpass")
+ /// <summary>
+ /// The constructor for the Database module.
+ /// </summary>
+ /// <param name="dispatcher">The Dispatcher this object will receive messages from.</param>
+ /// <param name="transmitters">The JSON file containing the sensor tag calibrations.</param>
+ /// <param name="host">The host name of the database to connect to.</param>
+ /// <param name="db">The name of the database to connect to.</param>
+ /// <param name="user">The username of the database to connect to.</param>
+ /// <param name="pass">The password for the user.</param>
+ public Database(Dispatcher dispatcher, dynamic config, string host = "localhost", string db = "csulbsha_sharktopus", string user = "testuser", string pass = "testpass")
+ :base(dispatcher)
{
connectionString = "Server=" + host + ";Database=" + db + ";Uid=" + user + ";Pwd=" + pass + ";";
+ updateSensorCalibrations(config);
+ logWriter = new System.IO.StreamWriter(config.log_file, true);
}
+ /// <summary>
+ /// Returns the human readable name of this module.
+ /// </summary>
+ /// <returns>The name of this module.</returns>
public override string getModuleName()
{ return "Database"; }
+
+ /// <summary>
+ /// Updates the list of of sensor tag calibrations from the JSON file. This should be called when the JSON file is updated.
+ /// </summary>
+ /// <param name="calibrations">The JSON file containing the calibration values.</param>
+ public void updateSensorCalibrations(dynamic config)
+ {
+ this.sensor_calibrations = new Dictionary<string, List<string>>();
+ foreach (string transmitter in config.transmitters.Keys)
+ {
+ List<string> temp = new List<string>(((string)config.transmitters[transmitter]).Split(','));
+ if (temp.Count == 3)
+ {
+ double test;
+ if (double.TryParse(temp[1], out test) && double.TryParse(temp[2], out test))
+ sensor_calibrations.Add((string)transmitter, temp);
+ }
+ }
+ }
+ /// <summary>
+ /// The hook for the event dispatcher. Determines the type of message, and if applicable, makes a database insertion.
+ /// </summary>
+ /// <param name="realTimeEvent"></param>
public override void onRealTimeEvent(RealTimeEvent realTimeEvent)
{
+ int response = 0;
if(realTimeEvent.GetType() == typeof(Decoder.RealTimeEvents.Decoded))
{
Decoder.RealTimeEvents.Decoded rte = (Decoder.RealTimeEvents.Decoded)realTimeEvent;
string eventType = rte["messagetype"];
if (eventType == "detection_event")
- detectionInsert(rte);
+ response = detectionInsert(rte);
+ else if (eventType == "status_response")
+ response = statusInsert(rte);
+ if (response > 1)
+ response = 1;
}
- else if(realTimeEvent.GetType() == typeof(ReceiverSlice.RealTimeEvents.NewReceiver))
- receiverInsert((ReceiverSlice.RealTimeEvents.NewReceiver)realTimeEvent);
+ //return response;
}
- private void receiverInsert(ReceiverSlice.RealTimeEvents.NewReceiver newReceiver)
+ // We are no longer responsible for populating the receivers table in the database with new receivers.
+ //private void receiverInsert(ReceiverSlice.RealTimeEvents.NewReceiver newReceiver)
+ //{
+ // string statement = "INSERT INTO receivers (id) VALUES ('" + newReceiver["serialnumber"] + "');";
+ // int response = doInsert(statement);
+ // dispatcher.enqueueEvent(new Databases.RealTimeEvents.DatabaseResponse(statement, response, newReceiver));
+ //}
+
+ /// <summary>
+ /// Makes an insertion into the vue table of the database for a detection event.
+ /// </summary>
+ /// <param name="detection">The RealTimeEvent object containing all necessary information from the detection.</param>
+ /// <returns>The number of rows affected by the insertion.</returns>
+ private int detectionInsert(Decoder.RealTimeEvents.Decoded detection)
{
- string statement = "INSERT INTO receivers (id) VALUES ('" + newReceiver["serialnumber"] + "');";
+ string date = detection["decodedmessage"]["date"];
+ string time = detection["decodedmessage"]["time"];
+ string frequency_codespace = detection["decodedmessage"]["frequency_codespace"];
+ string transmitter_id = detection["decodedmessage"]["transmitter_id"];
+ string receiver_model_id = detection["model"] + '-' + detection["serialnumber"];
+ string sensor_value = detection["decodedmessage"]["sensor_value"];
+ string sensor_type = "NULL";
+ string transmitter_codespace_id = frequency_codespace + '-' + transmitter_id;
+ if (sensor_value != "NULL")
+ {
+ if (sensor_calibrations.ContainsKey(transmitter_codespace_id))
+ {
+ sensor_type = '\'' + sensor_calibrations[transmitter_codespace_id][0] + '\'';
+ sensor_value = getCalibratedSensorValue(sensor_type, double.Parse(sensor_value), double.Parse(sensor_calibrations[transmitter_codespace_id][1]), double.Parse(sensor_calibrations[transmitter_codespace_id][2])).ToString();
+ }
+ else
+ sensor_type = "'A2D'";
+ }
+ string statement = "INSERT INTO vue (date, time, frequency_codespace, transmitter_id, sensor_value, sensor_unit, receivers_id) VALUES ('" +
+ date + "', '" + time + "', '" + frequency_codespace + "', " + transmitter_id + ", " + sensor_value + ", " + sensor_type + ", '" + receiver_model_id + "');";
int response = doInsert(statement);
- dispatcher.enqueueEvent(new Databases.RealTimeEvents.DatabaseResponse(statement, response, newReceiver));
+ dispatcher.enqueueEvent(new DatabaseResponse(statement, response, detection));
+ return response;
}
- private void detectionInsert(Decoder.RealTimeEvents.Decoded detection)
+ /// <summary>
+ /// Returns the calibrated value for the A2D value given as well as the type of reading and the coefficients.
+ /// </summary>
+ /// <param name="sensor_type">The type of measurement, for example "p", "t", or "m".</param>
+ /// <param name="raw_value">The A2D value.</param>
+ /// <param name="a">The high-order coefficient.</param>
+ /// <param name="b">The low-order coefficient.</param>
+ /// <returns>The calibrated value.</returns>
+ private double getCalibratedSensorValue(string sensor_type, double raw_value, double a, double b)
{
- string statement;
- if(detection["decodedmessage"]["sensor_value"] == null)
- statement = "INSERT INTO vue (date, time, frequency_codespace, transmitter_id, receivers_id) VALUES ('" +
- detection["decodedmessage"]["date"] + "', '" + detection["decodedmessage"]["time"] + "', '" + detection["decodedmessage"]["frequency_codespace"] + "', " + detection["decodedmessage"]["transmitter_id"] + ", '" + detection["decodedmessage"]["receivers_id"] + "');";
- else
- statement = "INSERT INTO vue (date, time, frequency_codespace, transmitter_id, sensor_value, sensor_unit, receivers_id) VALUES ('" +
- detection["decodedmessage"]["date"] + "', '" + detection["decodedmessage"]["time"] + "', '" + detection["decodedmessage"]["frequency_codespace"] + "', " + detection["decodedmessage"]["transmitter_id"] + ", " + detection["decodedmessage"]["sensor_value"] + ", 'm', '" + detection["decodedmessage"]["receivers_id"] + "');";
+ double calibratedValue = raw_value;
+ sensor_type = sensor_type.ToLower();
+ if (sensor_type == "t" || sensor_type == "m") //linear -- ax + b
+ calibratedValue = a * raw_value + b;
+ else if (sensor_type == "p") //quadratic -- ax² + b
+ calibratedValue = a * raw_value * raw_value + b;
+ return calibratedValue;
+ }
+
+ /// <summary>
+ /// Makes an insertion into the receiver_status table of the databse for a status event.
+ /// </summary>
+ /// <param name="status">The RealTimeEvent object containing all necessary information from the status event.</param>
+ /// <returns>The number of rows affected by the insertion.</returns>
+ private int statusInsert(Decoder.RealTimeEvents.Decoded status)
+ {
+ string receiver_model_id = status["model"] + '-' + status["serialnumber"];
+ string date = status["decodedmessage"]["date"];
+ string time = status["decodedmessage"]["time"];
+ string dc = status["decodedmessage"]["dc"];
+ string pc = status["decodedmessage"]["pc"];
+ string lv = status["decodedmessage"]["lv"];
+ string bv = status["decodedmessage"]["bv"];
+ string bu = status["decodedmessage"]["bu"];
+ string i = status["decodedmessage"]["i"];
+ string t = status["decodedmessage"]["t"];
+ string du = status["decodedmessage"]["du"];
+ string ru = status["decodedmessage"]["ru"];
+ string xyz = status["decodedmessage"]["xyz"];
+ if (xyz != "NULL")
+ xyz = '\'' + xyz + '\'';
+ string statement = "INSERT INTO receiver_status (id, date, time, detection_count, ping_count, line_voltage, battery_voltage, battery_used, current, temperature, detection_memory, raw_memory, xyz_orientation) VALUES ('" +
+ receiver_model_id + "', '" + date + "', '" + time + "', " + dc + ", " + pc + ", " + lv + ", " + bv + ", " + bu + ", " + i + ", " + t + ", " + du + ", " + ru + ", " + xyz + ");";
int response = doInsert(statement);
- dispatcher.enqueueEvent(new Databases.RealTimeEvents.DatabaseResponse(statement, response, detection));
+ dispatcher.enqueueEvent(new DatabaseResponse(statement, response, status));
+ return response;
}
+ /// <summary>
+ /// Attempts to make the actual insertion into the database.
+ /// </summary>
+ /// <param name="statement">The SQL statement to be performed on the database.</param>
+ /// <returns>The number of rows affected by the insertion.</returns>
private int doInsert(string statement)
{
int response = -1;
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand command;
- connection.Open();
try
{
+ connection.Open();
command = connection.CreateCommand();
command.CommandText = statement;
response = command.ExecuteNonQuery();
}
catch (Exception e)
- {}
+ {
+ logWriter.WriteLine("Insertion failure at " + DateTime.Now + ':');
+ logWriter.WriteLine("Statement: " + statement);
+ logWriter.WriteLine("Error: " + e.Message);
+ logWriter.WriteLine();
+ logWriter.Flush();
+ }
finally
{
- if(connection.State == ConnectionState.Open)
+ if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
return response;
}
}
-}
+}
@@ -26,7 +26,7 @@
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
- <OutputPath>bin\Release\</OutputPath>
+ <OutputPath>..\..\ConsoleServerRunner\ConsoleServerRunner\bin\Release\modules\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
@@ -0,0 +1,40 @@
+using EventSlice.Interfaces;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Databases.RealTimeEvents
+{
+ /// <summary>
+ /// Contains the response from the database after an attempted insertion as well as the command.
+ /// </summary>
+ public class DatabaseResponse: RealTimeEvent
+ {
+ public string sql { get; private set; }
+ public int response { get; private set; }
+
+ /// <summary>
+ /// Constructor for this event.
+ /// </summary>
+ /// <param name="message">The SQL non-query command (generally an INSERT).</param>
+ /// <param name="response">The number of rows affected. -1 indicates a failed insertion.</param>
+ /// <param name="originatingEvent">From whence this event came.</param>
+ public DatabaseResponse(string message, int response, RealTimeEvent originatingEvent)
+ :base("Database module: " + message, originatingEvent)
+ {
+ this.sql = message;
+ this.response = response;
+ }
+
+ /// <summary>
+ /// A string representation of this event.
+ /// </summary>
+ /// <returns>A string representation of this event.</returns>
+ public override string ToString()
+ {
+ return sql + '\n' + response + " rows affected.";
+ }
+ }
+}
Oops, something went wrong.

0 comments on commit e2b6351

Please sign in to comment.