Initial commit with all the cookiecutter files working

This commit is contained in:
Patrick McDonagh
2017-08-29 17:43:23 -05:00
commit fa946ee55d
11 changed files with 542 additions and 0 deletions

4
cookiecutter.json Normal file
View File

@@ -0,0 +1,4 @@
{
"driver_name": "pocloud_driver",
"driver_id": "0000"
}

View File

@@ -0,0 +1 @@
<module>Alerts</module>

View File

@@ -0,0 +1,6 @@
<div class='col-xs-1'>
<div class="<%= nodecolors.statuscolor %> nodecolor"></div>
</div>
<div class='col-xs-6'>
<h3><%= node.vanityname %></h3>
</div>

View File

@@ -0,0 +1,31 @@
<style>
.header h4 {
position: relative;
top: 0.9em;
}
.header h2 {
text-transform: uppercase;
font-size: 14px;
color: #aaa;
margin: 0.75em 0;
}
.header p {
font-size: 24px;
color: black;
font-weight: 600;
}
</style>
<div class="row header">
<div class="col-xs-1">
<div class="<%= nodecolors.statuscolor %> nodecolor"></div>
</div>
<div class="col-xs-2">
<img src="<%= nodeimgurl %>" />
</div>
<div class="col-xs-4">
<h4><%= node.vanityname %></h4>
</div>
</div>

View File

@@ -0,0 +1,121 @@
<div class="row row-flex box-me">
<div class="col-xs-12 text-center">
<h1>HEADER 1</h1>
</div>
<div class="col-xs-4 text-center">
<h2>CHANNEL 1</h2>
<div class="gauge-box">
<div data-labelheight="10"
style="height: 170px; background: transparent; margin: 0 auto;"
id="gauge-channel_1"
data-chart="solidgauge"
data-nodename="{{cookiecutter.driver_name}}.channel_1"
data-units="UNITS"
data-min="0"
data-max="100"
data-decimalplaces="2"
data-colors="0.1:#DF5353,0.5:#DDDF0D,0.9:#55BF3B"
data-valuefontsize="18px">
</div>
<div class- "timestamp-box">
<a href="#" data-channelId="<%= channels['{{cookiecutter.driver_name}}.channel_1'].channelId %>" class="data-table" title="Download Channel History">
<i class="fa fa-download"></i>
</a>
</div>
<span data-timeupdate="lt11_level">
<%= channels["{{cookiecutter.driver_name}}.channel_1"].timestamp %>
</span>
</div>
</div>
</div>
<style>
.box-me {
position: relative;
padding: 0.5em;
padding-bottom: 1.5em;
border: 1px solid #eee;
/*margin: 1em 0;*/
}
.box-me .gauge-box {
margin-top: -0.25em;
}
.pad15 {
margin: 15px 15px;
}
.box-me h2 {
text-transform: uppercase;
font-size: 14px;
color: #666;
font-weight: 400;
letter-spacing: 1px;
z-index: 100;
}
.dynamic-chart-form {
background-color: whiteSmoke;
padding: 1em 0.5em;
margin-top: 1em;
}
.row-flex {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
flex-wrap: wrap;
}
.row-flex > [class*='col-'] {
display: flex;
flex-direction: column;
}
#systemStatusTimelineContainer h2 {
text-transform: uppercase;
font-size: 14px;
color: #666;
font-weight: 400;
letter-spacing: 1px;
z-index: 100;
}
.slice.node-detail hr {
border-color: #ccc;
}
.slice.node-detail #alarms li {
margin-bottom: 1em;
padding: 0.5em;
}
.slice.node-detail #alarms li:nth-child(even){
background-color: whiteSmoke;
}
.slice.node-detail #alarms li span {
margin-left: 1em;
color: #aaa;
}
</style>
<script>
$('.val_box').each(function(topLevel){
$(this).change(function(){
var id = "#" + $(this).closest(".entry-top-level").attr('id');
if (id !== "#undefined"){
var val = $(id).find('.val_box').val();
var tag = $(id).find('.setstatic').attr('data-staticsend', val);
console.log($(id).find('.setstatic').attr('data-staticsend'));
}
});
});
</script>

View File

@@ -0,0 +1,15 @@
<a href="#"
data-channelId="<%= channels["{{cookiecutter.driver_name}}.log"].channelId %>"
class="data-table btn-block btn btn-theme animated"
title="Device Log"><i style='margin-left: 0.5em; cursor: pointer' class="fa fa-th-list icon-theme"></i> Device Log</a>
<a href="#"
data-refreshpause="1"
data-staticsend="1"
data-channelId="<%= channels["{{cookiecutter.driver_name}}.sync"].channelId %>"
data-techname="<%=channels["{{cookiecutter.driver_name}}.sync"].techName %>"
data-name="<%= channels["{{cookiecutter.driver_name}}.sync"].name%>"
data-nodechannelcurrentId="<%= channels["{{cookiecutter.driver_name}}.sync"].nodechannelcurrentId %>"
id="<%= channels["{{cookiecutter.driver_name}}.sync"].channelId %>"
class="btn btn-large btn-block btn-theme animated setstatic mqtt">
<i class="icon-repeat icon-white mqtt" ></i>Sync All Data</a>

View File

@@ -0,0 +1,37 @@
<div class='col-xs-12' style="padding-top: 1em; margin-bottom: 1em;">
<div class="input-daterange input-group" id="datepicker">
<input data-chartid="dynamicChart" id="fromDate" data-daysofhistory="7" type="text" class="form-control" name="start">
<span class="input-group-addon">to</span>
<input class="form-control" data-chartid="dynamicChart" id="toDate" type="text" name="end">
<span class='input-group-btn'>
<a href="#!" data-chartid="dynamicChart" data-otherchartids="statusTimeline" class="btn chart-update btn-theme">Run</a>
</span>
</div>
</div>
<hr>
<div class='clearfix col-xs-12'
style='height: 450px'
id="dynamicChart"
data-chart="dynamicchart"
data-daysofhistory="7"
data-chartlabel="Data"
data-ylabel=""
data-xlabel="Date"
data-units=""
data-channelnames="{{cookiecutter.driver_name}}.channel_1,">
</div>
<style>
.dynamic-chart-form {
background-color: whiteSmoke;
padding: 1em 0.5em;
margin-top: 1em;
}
#systemStatusTimelineContainer h2 {
text-transform: uppercase;
font-size: 14px;
color: #666;
font-weight: 400;
letter-spacing: 1px;
z-index: 100;
}
</style>

View File

@@ -0,0 +1,211 @@
"""Define Meshify channel class."""
from pycomm.ab_comm.clx import Driver as ClxDriver
from pycomm.cip.cip_base import CommError, DataError
import time
def binarray(intval):
"""Split an integer into its bits."""
bin_string = '{0:08b}'.format(intval)
bin_arr = [i for i in bin_string]
bin_arr.reverse()
return bin_arr
def read_tag(addr, tag):
"""Read a tag from the PLC."""
c = ClxDriver()
try:
if c.open(addr):
try:
v = c.read_tag(tag)
return v
except DataError:
c.close()
print("Data Error during readTag({}, {})".format(addr, tag))
except CommError:
# err = c.get_status()
c.close()
print("Could not connect during readTag({}, {})".format(addr, tag))
# print err
except AttributeError as e:
c.close()
print("AttributeError during readTag({}, {}): \n{}".format(addr, tag, e))
c.close()
return False
def read_array(addr, tag, start, end):
"""Read an array from the PLC."""
c = ClxDriver()
if c.open(addr):
arr_vals = []
try:
for i in range(start, end):
tag_w_index = tag + "[{}]".format(i)
v = c.read_tag(tag_w_index)
# print('{} - {}'.format(tag_w_index, v))
arr_vals.append(round(v[0], 4))
# print(v)
if len(arr_vals) > 0:
return arr_vals
else:
print("No length for {}".format(addr))
return False
except Exception:
print("Error during readArray({}, {}, {}, {})".format(addr, tag, start, end))
err = c.get_status()
c.close()
print err
pass
c.close()
def write_tag(addr, tag, val):
"""Write a tag value to the PLC."""
c = ClxDriver()
if c.open(addr):
try:
cv = c.read_tag(tag)
wt = c.write_tag(tag, val, cv[1])
return wt
except Exception:
print("Error during writeTag({}, {}, {})".format(addr, tag, val))
err = c.get_status()
c.close()
print err
c.close()
class Channel:
"""Holds the configuration for a Meshify channel."""
def __init__(self, ip, mesh_name, plc_tag, data_type, chg_threshold, guarantee_sec, map_=False, write_enabled=False):
"""Initialize the channel."""
self.plc_ip = ip
self.mesh_name = mesh_name
self.plc_tag = plc_tag
self.data_type = data_type
self.last_value = None
self.value = None
self.last_send_time = 0
self.chg_threshold = chg_threshold
self.guarantee_sec = guarantee_sec
self.map_ = map_
self.write_enabled = write_enabled
def __str__(self):
"""Create a string for the channel."""
return "{}: {}\nvalue: {}, last_send_time: {}".format(self.mesh_name, self.plc_tag, self.value, self.last_send_time)
def read(self, force_send=False):
"""Read the value and check to see if needs to be stored."""
send_needed = False
send_reason = ""
if self.plc_tag:
v = read_tag(self.plc_ip, self.plc_tag)
if v:
if self.data_type == 'BOOL' or self.data_type == 'STRING':
if self.last_send_time == 0:
send_needed = True
send_reason = "no send time"
elif self.value is None:
send_needed = True
send_reason = "no value"
elif not (self.value == v[0]):
if self.map_:
if not self.value == self.map_[v[0]]:
send_needed = True
send_reason = "value change"
else:
send_needed = True
send_reason = "value change"
elif (time.time() - self.last_send_time) > self.guarantee_sec:
send_needed = True
send_reason = "guarantee sec"
elif force_send:
send_needed = True
send_reason = "forced"
else:
if self.last_send_time == 0:
send_needed = True
send_reason = "no send time"
elif self.value is None:
send_needed = True
send_reason = "no value"
elif abs(self.value - v[0]) > self.chg_threshold:
send_needed = True
send_reason = "change threshold"
elif (time.time() - self.last_send_time) > self.guarantee_sec:
send_needed = True
send_reason = "guarantee sec"
elif force_send:
send_needed = True
send_reason = "forced"
if send_needed:
self.last_value = self.value
if self.map_:
try:
self.value = self.map_[v[0]]
except KeyError:
print("Cannot find a map value for {} in {} for {}".format(v[0], self.map_, self.mesh_name))
self.value = v[0]
else:
self.value = v[0]
self.last_send_time = time.time()
print("Sending {} for {} - {}".format(self.value, self.mesh_name, send_reason))
return send_needed
class BoolArrayChannels(Channel):
"""Hold the configuration for a set of boolean array channels."""
def compare_values(self, new_val_dict):
"""Compare new values to old values to see if the values need storing."""
send = False
for idx in new_val_dict:
try:
if new_val_dict[idx] != self.last_value[idx]:
send = True
except KeyError:
print("Key Error in self.compare_values for index {}".format(idx))
send = True
return send
def read(self, force_send=False):
"""Read the value and check to see if needs to be stored."""
send_needed = False
send_reason = ""
if self.plc_tag:
v = read_tag(self.plc_ip, self.plc_tag)
if v:
bool_arr = binarray(v[0])
new_val = {}
for idx in self.map_:
try:
new_val[self.map_[idx]] = bool_arr[idx]
except KeyError:
print("Not able to get value for index {}".format(idx))
if self.last_send_time == 0:
send_needed = True
send_reason = "no send time"
elif self.value is None:
send_needed = True
send_reason = "no value"
elif self.compare_values(new_val):
send_needed = True
send_reason = "value change"
elif (time.time() - self.last_send_time) > self.guarantee_sec:
send_needed = True
send_reason = "guarantee sec"
elif force_send:
send_needed = True
send_reason = "forced"
if send_needed:
self.value = new_val
self.last_value = self.value
self.last_send_time = time.time()
print("Sending {} for {} - {}".format(self.value, self.mesh_name, send_reason))
return send_needed

View File

@@ -0,0 +1,3 @@
"""Holds map values for {{cookiecutter.driver_name}}."""
{{cookiecutter.driver_name}}_map = {}

View File

@@ -0,0 +1,14 @@
{
"driverFileName":"{{cookiecutter.driver_name}}.py",
"deviceName":"{{cookiecutter.driver_name}}",
"driverId":"{{cookiecutter.driver_id}}",
"releaseVersion":"1",
"files": {
"file1":"{{cookiecutter.driver_name}}.py",
"file2":"Channel.py",
"file3":"Maps.py",
"file4":"Scheduler.py"
}
}

View File

@@ -0,0 +1,99 @@
"""Driver for {{cookiecutter.driver_name}}"""
import threading
from device_base import deviceBase
from Channel import Channel, write_tag, BoolArrayChannels
from Maps import {{cookiecutter.driver_name}}_map as maps
import json
import time
_ = None
try:
with open("persist.json", 'r') as persist_file:
persist = json.load(persist_file)
except Exception:
persist = {}
plc_ip_address = "192.168.1.10"
def reverse_map(value, map_):
"""Perform the opposite of mapping to an object."""
for x in map_:
if map_[x] == value:
return x
return None
channels = []
class start(threading.Thread, deviceBase):
"""Start class required by Meshify."""
def __init__(self, name=None, number=None, mac=None, Q=None, mcu=None, companyId=None, offset=None, mqtt=None, Nodes=None):
"""Initialize the driver."""
threading.Thread.__init__(self)
deviceBase.__init__(self, name=name, number=number, mac=mac, Q=Q, mcu=mcu, companyId=companyId, offset=offset, mqtt=mqtt, Nodes=Nodes)
self.daemon = True
self.version = "3"
self.finished = threading.Event()
self.forceSend = False
threading.Thread.start(self)
# this is a required function for all drivers, its goal is to upload some piece of data
# about your device so it can be seen on the web
def register(self):
"""Register the driver."""
# self.sendtodb("log", "BOOM! Booted.", 0)
pass
def run(self):
"""Actually run the driver."""
global persist
wait_sec = 60
for i in range(0, wait_sec):
print("{{cookiecutter.driver_name}} driver will start in {} seconds".format(wait_sec - i))
time.sleep(1)
print("BOOM! Starting {{cookiecutter.driver_name}} driver...")
# after its booted up assuming that M1 is now reading modbus data
# we can replace the reference made to this device name to the M1 driver with this
# driver. The 01 in the 0199 below is the device number you referenced in the modbus wizard
self.nodes["{{cookiecutter.driver_name}}_0199"] = self
send_loops = 0
while True:
if self.forceSend:
print "FORCE SEND: TRUE"
for c in channels:
if c.read(self.forceSend):
self.sendtodb(c.mesh_name, c.value, 0)
# print("{{cookiecutter.driver_name}} driver still alive...")
if self.forceSend:
if send_loops > 2:
print("Turning off forceSend")
self.forceSend = False
send_loops = 0
else:
send_loops += 1
def {{cookiecutter.driver_name}}_sync(self, name, value):
"""Sync all data from the driver."""
self.forceSend = True
# self.sendtodb("log", "synced", 0)
return True
def {{cookiecutter.driver_name}}_writeplctag(self, name, value):
"""Write a value to the PLC."""
new_val = json.loads(str(value).replace("'", '"'))
tag_n = str(new_val['tag']) # "cmd_Start"
val_n = new_val['val']
w = write_tag(str(plc_ip_address), tag_n, val_n)
print("Result of {{cookiecutter.driver_name}}_writeplctag(self, {}, {}) = {}".format(name, value, w))
if w is None:
w = "Error writing to PLC..."
return w