code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
import re
import json
from typing import List, Dict, Any
import websockets
import brotli
from Arcapi.api import Api
from Arcapi.exceptions import *
class AsyncApi(Api):
user_code: str # User's 9-digit code for login
start: int # The beginning constant for consulting
end: int # The ending constant for consulting
timeout: int # The time for connecting wss
def __init__(self, user_code: str, start: int = 8, end: int = 12, timeout: int = 5) -> None:
self.ws_endpoint = 'wss://arc.estertion.win:616'
if not re.fullmatch(r'\d{9}', user_code):
raise ArcInvaidUserCodeException
self.user_code = user_code
self.start = start
self.end = end
self.timeout = timeout
async def call_action(self, action: str, **params) -> Any:
if 'start' in params:
_start = params['start']
else:
_start = self.start
if 'end' in params:
_end = params['end']
else:
_end = self.end
container: List[Dict] = [] # The result list for request objects
async with websockets.connect(self.ws_endpoint, timeout=self.timeout) as conn:
await conn.send(f'{self.user_code} {_start} {_end}')
_recv = await conn.recv()
if _recv == 'invalid id':
raise ArcInvaidUserCodeException
elif _recv == 'queried':
while True:
_r = await conn.recv()
if isinstance(_r, str) and _r == 'bye':
break
elif isinstance(_r, (bytes, bytearray)):
_data = json.loads(brotli.decompress(_r))
if _data['cmd'] == action:
if type(_data['data']) is list:
for _item in _data['data']:
container.append(_item)
else:
container.append(_data['data'])
else:
raise ArcUnknownException(_recv)
return container
|
Arc-api
|
/Arc_api-1.1.tar.gz/Arc_api-1.1/Arcapi/async_api.py
|
async_api.py
|
from win32com.client import Dispatch
import os, sys, re, time, shutil # removed: tempfile, preferable to use win32api.GetTempFileName anyways
# debug options
debug = 0 # 1 or 0
if debug:
fxn = 'glm' # 'glm' , 'cart' or 'gam'
prefix = 'D:/projects/ArcRstats/'
in_obs = prefix + 'sp_obs.shp'
in_rnd = prefix + 'sp_rnd.shp'
in_rnames = ['dem', 'aspect', 'tci', 'landcov']
sep = ';' + prefix
in_rasters = prefix + sep.join(in_rnames)
out_mdl = prefix + 'out_' + fxn
out_tbl_obs = out_mdl + '_smpl_obs.dbf'
out_tbl_rnd = out_mdl + '_smpl_rnd.dbf'
class RModel:
def __init__(self):
pass
def msg(self, msg):
# utility message function
self.gp.AddMessage(msg) # print to geoprocessor
print msg # print to console
self.rlog.write('# %s\n' % msg) # append to log file
def rcmd(self, cmd):
# utility R command function
try:
self.r.EvaluateNoReturn(cmd) # run command
except:
self.msg('Unexpected error with R command...\n' + str(cmd) + '\n' + str(self.r.GetErrorText()) + '\n' + str(sys.exc_info()[0]))
raise
#sys.exit()
self.rlog.write(cmd+'\n') # append to log file
def initialize(self):
# initialization calls
# get input variables
global fxn
self.fxn = fxn # input, function to use in modeling
# comment below to debug
if debug:
global in_obs, in_rnd, in_rasters, out_mdl, out_tbl_obs, out_tbl_rnd
self.in_obs = in_obs
self.in_rnd = in_rnd
self.in_rasters = in_rasters
self.out_mdl = out_mdl
self.out_tbl_obs = out_tbl_obs
self.out_tbl_rnd = out_tbl_rnd
else:
for i in range(0,len(sys.argv)):
if isinstance(sys.argv[i],str):
sys.argv[i] = sys.argv[i].replace('\\','/')
self.in_obs = sys.argv[2] # input, observed points featureclass
self.in_rnd = sys.argv[3] # input, random points featureclass
self.in_rasters = sys.argv[4] # input, multiple rasters
## self.out_mdl = os.path.dirname(sys.argv[5]) + '/' + os.path.basename(sys.argv[5]) # output modeled raster
## self.out_tbl_obs = os.path.dirname(sys.argv[6]) + '/' + os.path.basename(sys.argv[6]) # output sampled obs dbf
## self.out_tbl_rnd = os.path.dirname(sys.argv[7]) + '/' + os.path.basename(sys.argv[7]) # output sampled rnd dbf
self.out_mdl = sys.argv[5] # output modeled raster
self.out_tbl_obs = sys.argv[6] # output sampled obs dbf
self.out_tbl_rnd = sys.argv[7] # output sampled rnd dbf
# assign other output filenames
self.cwd = os.path.dirname(self.out_mdl)
self.samplesfile = self.out_mdl + '_samples.txt'
self.rlogfile = self.out_mdl + '_log.r'
# open r_log
self.rlog = open(self.rlogfile, 'w')
self.rlog.write('# ' + self.fxn.upper() + ' started on ' + time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) + '\n')
# initialize geoprocessor
self.gp = Dispatch("esriGeoprocessing.GpDispatch.1")
self.gp.CheckOutExtension("Spatial")
self.gp.OverwriteOutput = 1 # setup for overwrite
# initialize R stats
self.r = Dispatch("StatConnectorSrv.StatConnector")
self.r.Init("R")
# setup dictionary list variables
self.msg(' setup variables...')
self.rasters = {} # dictionary of raster paths by raster name
self.samples = {} # dictionary of sample value lists by raster name
self.samples['obs'] = [] # known response sample value list
for path in self.in_rasters.split(';'):
path = path.replace("'","");
name = os.path.basename(path)
self.rasters[name] = path
self.samples[name] = []
def sample2r(self):
self.msg(' sample rasters...')
# sample across rasters for observed and random locations
try:
self.gp.Sample_sa(';'.join(self.rasters.values()), self.in_obs, self.out_tbl_obs, 'NEAREST')
self.gp.Sample_sa(';'.join(self.rasters.values()), self.in_rnd, self.out_tbl_rnd, 'NEAREST')
except:
print 'ERROR: ' + self.gp.GetMessages()
# read in sampled presence (observation) tables
self.msg(' read in sampled presence tables...')
rows = self.gp.SearchCursor(self.out_tbl_obs)
row = rows.Next()
while row:
self.samples['obs'].append('present') # set to 1 for obs, 0 for rnd
for col in self.rasters.keys(): # iterate through sampled columns
self.samples[col].append(row.GetValue(col))
row = rows.Next() # advance to next row
# read in sampled absence (random) tables
self.msg(' read in sampled absence/random tables...')
rows = self.gp.SearchCursor(self.out_tbl_rnd)
row = rows.Next()
while row:
self.samples['obs'].append('absent') # set to 1 for obs, 0 for rnd
for col in self.rasters.keys(): # iterate through sampled columns
self.samples[col].append(row.GetValue(col))
row = rows.Next() # advance to next row
# write out samplesfile.txt
f=open(self.samplesfile, 'w')
for i in range(len(self.samples['obs'])):
rowdata = []
for k in self.samples.keys():
if i == 0: # header row
rowdata.append(str(k))
else:
v = str(self.samples[k][i])
rowdata.append(v)
sep = ','
f.write(sep.join(rowdata) + '\n')
f.close()
# read into R
#self.rcmd('dat <- read.table("' + self.samplesfile.replace('\\','/') + '", header=TRUE, sep = ",", na.strings = "-9999.0")')
self.rcmd('dat <- read.table("' + self.samplesfile + '", header=TRUE, sep = ",", na.strings = "-9999.0")')
del(self.samples) # clean up python memory
def grids2r(self):
# feed grid data to R
self.msg(' feed grid data to R for predicting with model...')
# find grid with largest cellsize
cellwidth = 0
self.cellsizes = {}
self.extents = {}
self.sprefs = {}
for n,p in self.rasters.items():
descr = self.gp.Describe(p)
self.cellsizes[n] = str(descr.MeanCellWidth)
self.extents[n] = str(descr.Extent)
self.sprefs[n] = descr.SpatialReference
if descr.MeanCellWidth > cellwidth:
# assign as template raster
self.template = n
self.msg(' template grid with largest cell size: ' + n)
# set environment based on cellraster
self.gp.Workspace = self.cwd
self.gp.OutputCoordinateSystem = self.sprefs[self.template]
self.gp.Extent = self.extents[self.template] # snap grid
self.msg(' resample other grids, if different cellsize/extent from template...')
# resample and size, if necessary
for n,p in self.rasters.items():
if self.cellsizes[n] <> self.cellsizes[self.template] or self.extents[n] <> self.extents[self.template]:
try:
if self.gp.Exists(p + '_r'):
self.gp.Delete(p + '_r')
self.gp.Resample(p, p + '_r', self.cellsizes[self.template], 'NEAREST')
#gp.Clip(p + '_r', cellextent, p + '_c')
except:
print self.gp.GetMessages()
# assign resampled/resized raster path to rasters dictionary
self.rasters[n] = p+'_r'
# output to ascii, read into R
self.msg(' output grids to temporary ASCII files and read into R...')
self.rasters_asc = self.rasters.copy()
for n,p in self.rasters.items():
# output to ascii
p_asc = p + '.asc'
self.rasters_asc[n] = p_asc
try:
self.gp.RasterToASCII_conversion(p, p_asc)
except:
self.msg(self.gp.GetMessages())
# read ascii table into R as a vector for model prediction
self.rcmd(n + ' <- read.table("' + self.rasters_asc[n].replace('\\','/') + '", sep=" ", na.strings="-9999", skip=6)')
self.rcmd(n + ' <- as.vector(data.matrix(' + n + '[-length(' + n + ')]))') # exclude trailing column created by extra space in RasterToASCII output
# get header information from template for outputting model prediction from R to ASCII ArcGIS Raster format
self.header = {}
if n == self.template:
# read in header info
f=open(self.rasters_asc[n], 'r')
self.header['ncols'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['nrows'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['xllcorner'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['yllcorner'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['cellsize'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['NODATA_value'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
f.close()
# write out header info to output model grid ascii file
self.out_mdl_ascii = self.out_mdl + '.asc'
f=open(self.out_mdl_ascii, 'w')
for k, v in self.header.items():
f.write('%s %s\n' % (k, v))
f.close()
# bind to data frame in R
sep = ', '
self.rcmd('datpred <- data.frame(cbind(' + sep.join(self.rasters.keys()) + '))')
# clear old variables from R session memory
for n in self.rasters.keys():
self.rcmd('rm('+n+')')
def pred2gis(self):
# expects a predict object named 'pred' in R
self.msg(' convert model prediction to grid...')
self.rcmd('write.table(pred, file="' + self.out_mdl_ascii.replace('\\','/') + '", append=TRUE, sep=" ", col.names=FALSE, row.names=FALSE, na="-9999")')
try:
if self.gp.Exists(self.out_mdl):
self.gp.Delete(self.out_mdl)
self.gp.ASCIIToRaster_conversion(self.out_mdl_ascii, self.out_mdl, "FLOAT")
self.gp.Toolbox = "Management"
# this should work, but the SpatialReference returns an object, not the expected *.prj file DefineProjection wants
#self.gp.DefineProjection(self.out_mdl, self.sprefs[template])
except:
print self.gp.GetMessages()
# project model raster by copying prj.adf
prj = self.rasters[self.template] + '/prj.adf'
if os.path.exists(prj):
shutil.copyfile(prj, self.out_mdl + '/prj.adf')
def plotsamples(self):
self.rcmd('plotpre <- "' + self.out_mdl.replace('\\','/') + '"')
self.rcmd('datenv <- dat[,names(dat)!="obs"]')
self.rcmd('png(paste(sep='', plotpre, "_plotpairs.png"))')
self.rcmd('pairs(datenv, main="Correlations Between Variables")')
self.rcmd('dev.off()')
self.rcmd('''for (c in names(datenv)){
denspres <- density(na.exclude(dat[dat[["obs"]]==1, c]))
densabs <- density(na.exclude(dat[dat[["obs"]]==0, c]))
xlim <- range(na.exclude(dat[, c]))
ylim <- c(0,max(c(denspres$y, densabs$y)))
#png(filename=filename, width=600, height=400, pointsize=1, bg="white", res=200)
png(paste(sep='', plotpre, '_hist_', c, '.png'))
plot(denspres, type='l', main=paste(c,'Distribution'), xlab=c, ylab='Density', ylim=ylim, xlim=xlim)
lines(densabs, lty=2)
legend(x=xlim[1], y=ylim[2], legend=c('presence', 'absence'), lty=1:2)
dev.off()
}''')
def finalize(self):
# clean up temp files
## if not debug:
## for n,p in self.rasters_asc.items():
## os.unlink(p)
# close r
self.r.Close()
self.rlog.close()
# close gp
del(self.gp)
class GLM(RModel):
def __init__(self):
# initialize
self.initialize()
# sample data
self.sample2r()
self.plotsamples()
# build model
self.msg(' generate GLM in R...')
self.rcmd('dat$obs <- factor(dat$obs)')
self.rcmd('dat <- na.exclude(dat)')
self.rcmd('mdlall <- glm(obs ~ ., data=dat, family=binomial(link="logit"))')
self.msg(' find best GLM model by AIC...')
self.rcmd('library(MASS)')
self.rcmd('mdl <- stepAIC(mdlall, trace=F)')
# save model summaries
self.rcmd('sink("' + self.out_mdl.replace('\\','/') + '_summary.txt")')
self.rcmd('cat("\nGLM all..\n\n")')
self.rcmd('print(summary(mdlall))')
self.rcmd('cat("\nGLM best model, with step-wise AIC selection of coefficients...\n\n")')
self.rcmd('print(summary(mdl))')
self.rcmd('sink()')
# grid data
self.grids2r()
# predict with model
self.msg(' predict GLM in R...')
#self.rcmd('rowsna <- sort(unique(which(is.na(datpred), arr.ind=TRUE)[,1]))')
#self.rcmd('datpred <- na.exclude(datpred)')
self.rcmd('pred <- predict(mdl, newdata=datpred, na.action=na.pass, type="response")')
#self.rcmd('''for (row in rowsna){
# pred <- append(pred, NA, row-1)
# }''')
self.rcmd('dim(pred) <- c(' + self.header['nrows'] + ', ' + self.header['ncols'] + ')')
# save model and data
self.rcmd('save(dat, mdlall, mdl, datpred, pred, file = "' + self.out_mdl.replace('\\','/') + '.rdata")')
# prediction to grid
self.pred2gis()
self.finalize()
class GLM2(RModel):
def __init__(self):
# initialize
self.initialize()
# sample data
self.sample2r()
## self.plotsamples()
# build model
self.msg(' generate GLM in R...')
self.rcmd('dat$obs <- factor(dat$obs)')
self.rcmd('dat <- na.exclude(dat)')
self.rcmd('mdlall <- glm(obs ~ ., data=dat, family=binomial(link="logit"))')
self.msg(' find best GLM model by AIC...')
self.rcmd('library(MASS)')
self.rcmd('mdl <- stepAIC(mdlall, trace=F)')
# save model summaries
#self.rcmd('sink("' + self.out_mdl.replace('\\','/') + '_summary.txt")')
self.rcmd('sink("' + self.out_mdl + '_summary.txt")')
self.rcmd('cat("\nGLM all..\n\n")')
self.rcmd('print(summary(mdlall))')
self.rcmd('cat("\nGLM best model, with step-wise AIC selection of coefficients...\n\n")')
self.rcmd('print(summary(mdl))')
self.rcmd('sink()')
# grid data
#self.grids2r() # skipping
# predict with model
self.msg(' extract GLM coefficients from R...')
coeffs = {}
coeffs_d = self.r.Evaluate('summary(mdl)$coefficients')
coeffs_r = self.r.Evaluate('rownames(summary(mdl)$coefficients)')
coeffs_c = self.r.Evaluate('colnames(summary(mdl)$coefficients)')
for i in range(0, len(coeffs_r)):
coeffs[coeffs_r[i]] = dict([(coeffs_c[j], coeffs_d[i][j]) for j in range(0, len(coeffs_c))])
# formulate expression for map algebra
in_rasters = []; expression = []
for r in coeffs.keys():
if r=='(Intercept)':
expression.append(str(coeffs[r]['Estimate']))
else:
expression.append('(' + str(coeffs[r]['Estimate']) + ' * ' + self.rasters[r] + ')')
in_expression = ' + '.join(expression)
try:
self.gp.SingleOutputMapAlgebra_sa(in_expression, self.out_mdl)
except:
print 'ERROR: ' + self.gp.GetMessages()
# save model and data
self.rcmd('save(file="' + self.out_mdl + '.rdata")')
# prediction to grid
#self.pred2gis()
#self.finalize()
class GAM(RModel):
def __init__(self):
# initialize
self.initialize()
# sample data
self.sample2r()
self.plotsamples()
# construct formula
self.msg(' generate GAM formula...')
terms = []
for k in self.rasters.keys():
terms.append('s(' + k + ', bs="ts")')
sep = ' + '
formula = 'obs ~ ' + sep.join(terms)
# build model
self.msg(' generate GAM in R...')
self.rcmd('dat$obs <- factor(dat$obs)')
self.rcmd('library(mgcv)')
self.rcmd('mdl <- gam(' + formula + ', data=dat, family=binomial(link="logit"))')
# save model summary and graphics
self.rcmd('sink("' + self.out_mdl.replace('\\','/') + '_summary.txt")')
self.rcmd('cat("\nGAM..\n\n")')
self.rcmd('print(summary(mdl))')
self.rcmd('sink()')
self.rcmd('png("' + self.out_mdl.replace('\\','/') + '_plot.png")')
self.rcmd('plot(mdl,pages=1,residuals=TRUE,all.terms=TRUE,shade=TRUE,shade.col="gray")')
self.rcmd('dev.off()')
# grid data
self.grids2r()
# predict with model
self.msg(' predict with GAM in R...')
self.rcmd('rowsna <- sort(unique(which(is.na(datpred), arr.ind=TRUE)[,1]))')
self.rcmd('datpred <- na.exclude(datpred)')
self.rcmd('pred <- predict(mdl, newdata=datpred, type="response", block.size=0.5, newdata.guaranteed=FALSE)')
self.rcmd('''for (row in rowsna){
pred <- append(pred, NA, row-1)
}''')
self.rcmd('dim(pred) <- c(' + self.header['nrows'] + ', ' + self.header['ncols'] + ')')
# save model and data
self.rcmd('save(dat, mdl, datpred, pred, file = "' + self.out_mdl.replace('\\','/') + '.rdata")')
# prediction to grid
self.pred2gis()
self.finalize()
class CART(RModel):
def __init__(self):
# initialize
self.initialize()
# sample data
self.sample2r()
self.plotsamples()
# build model
self.msg(' generate CART in R...')
self.rcmd('dat$obs <- factor(dat$obs)')
self.rcmd('library(rpart)')
self.rcmd('mdlall <- rpart(obs ~ ., data=dat, control=rpart.control(cp=0), method="class")')
self.rcmd('mdlall.cp <- mdlall$cptable[mdlall$cptable[,4] == min(mdlall$cptable[,4]), 1]')
self.msg(' trim CART (complexity parameter with minimum cross-validation error)...')
self.rcmd('mdl <- rpart(obs ~ ., data=dat, control=rpart.control(cp=mdlall.cp), na.action=na.pass, method="class")')
# save model summary and graphics
self.msg(' plot CART tree from R...')
self.rcmd('png("' + self.out_mdl.replace('\\','/') + '_tree.png")')
self.rcmd('plot(mdl)')
self.rcmd('text(mdl, use.n=TRUE)')
self.rcmd('dev.off()')
self.rcmd('sink("' + self.out_mdl.replace('\\','/') + '_summary.txt")')
self.rcmd('cat("\nFull CART (cp=0)...\n\n")')
self.rcmd('print(summary(mdlall))')
self.rcmd('cat("\n\nModified CART (using",str(mdlall.cp),"as complexity parameter from Full CART)...\n\n")')
self.rcmd('print(summary(mdl))')
self.rcmd('sink()')
# grid data
self.grids2r()
# predict with model
self.msg(' predict CART in R...')
self.rcmd('pred <- predict(mdl, newdata=datpred, na.action=na.pass, type="prob")[,2]') # the probability of it being the second answer ( = 1 = presence)
self.rcmd('dim(pred) <- c(' + self.header['nrows'] + ', ' + self.header['ncols'] + ')')
# save model and data
self.rcmd('save(dat, mdl, datpred, pred, file = "' + self.out_mdl.replace('\\','/') + '.rdata")')
# prediction to grid
self.pred2gis()
self.finalize()
class CART2(RModel):
def __init__(self):
# initialize
self.initialize()
# sample data
## self.sample2r()
self.rcmd('dat <- read.table("' + self.samplesfile + '", header=TRUE, sep = ",", na.strings = "-9999.0")')
## self.plotsamples()
## # build model
## self.msg(' generate CART in R...')
## self.rcmd('dat$obs <- factor(dat$obs)')
## self.rcmd('library(rpart)')
## self.rcmd('mdlall <- rpart(obs ~ ., data=dat, control=rpart.control(cp=0), method="class")')
## self.rcmd('mdlall.cp <- mdlall$cptable[mdlall$cptable[,4] == min(mdlall$cptable[,4]), 1]')
## self.msg(' trim CART (complexity parameter with minimum cross-validation error)...')
## self.rcmd('mdl <- rpart(obs ~ ., data=dat, control=rpart.control(cp=mdlall.cp), na.action=na.pass, method="class")')
##
## # save model summary and graphics
## self.msg(' plot CART tree from R...')
## self.rcmd('png("' + self.out_mdl.replace('\\','/') + '_tree.png")')
## self.rcmd('plot(mdl, margin=.05)')
## self.rcmd('text(mdl, use.n=TRUE, cex=.6)')
## self.rcmd('dev.off()')
## self.rcmd('sink("' + self.out_mdl + '_summary.txt")')
## self.rcmd('cat("\nFull CART (cp=0)...\n\n")')
## self.rcmd('print(summary(mdlall))')
## self.rcmd('cat("\n\nModified CART (using",str(mdlall.cp),"as complexity parameter from Full CART)...\n\n")')
## self.rcmd('print(summary(mdl))')
## self.rcmd('sink()')
# build model
#self.gp.Workspace = r'M:\projects\ArcRstats\ArcRstats\example\data'
self.msg(' generate CART in R...')
self.rcmd('library(rpart)')
self.rcmd('mdl <- rpart(obs ~ ., data=dat, method="class")')
self.rcmd('inodes = rownames(mdl$frame[mdl$frame$var=="<leaf>",])')
self.rcmd('lnodes = length(inodes)')
self.rcmd('paths = path.rpart(mdl, inodes, print.it=F)')
self.rcmd('formulas = character(lnodes)')
self.r.SetSymbol('raster.names',self.rasters.keys())
self.r.SetSymbol('raster.paths',self.rasters.values())
self.rcmd('''for (i in 1:lnodes){
ps = paths[[i]][-1]
for (j in 1:length(ps)){
for (k in 1:length(raster.names)){
ps[j] = sub(raster.names[k],raster.paths[k], ps[j])
}
}
formulas[i] = paste(ps, collapse=" & ")
}''')
formulas = self.r.Evaluate('formulas')
algebra = ''
for i in range(0,len(formulas)):
f = formulas[i]
algebra += 'con(' + f + ',' + str(i+1) + ','
algebra += '0' + ')'*len(formulas)
try:
self.gp.SingleOutputMapAlgebra_sa(algebra, self.out_mdl)
except:
print 'ERROR: ' + self.gp.GetMessages()
## # grid data
## self.grids2r()
##
## # predict with model
## self.msg(' predict CART in R...')
## self.rcmd('pred <- predict(mdl, newdata=datpred, na.action=na.pass, type="prob")[,2]') # the probability of it being the second answer ( = 1 = presence)
## self.rcmd('dim(pred) <- c(' + self.header['nrows'] + ', ' + self.header['ncols'] + ')')
## # save model and data
## self.rcmd('save(file="' + self.out_mdl + '.rdata")')
## # prediction to grid
## self.pred2gis()
## self.finalize()
if __name__ == "__main__":
# main call
if not debug:
fxn = sys.argv[1] # function switch as first argument
if fxn == 'glm':
GLM()
elif fxn == 'glm2':
GLM2()
elif fxn == 'gam':
GAM()
elif fxn == 'cart':
CART()
elif fxn == 'cart2':
CART2()
|
ArcRstats
|
/ArcRstats-0.8.alpha.zip/ArcRstats-0.8.alpha/arc_r/ArcRstats_1.py
|
ArcRstats_1.py
|
from win32com.client import Dispatch
import os, sys, re, time, shutil # removed: tempfile, preferable to use win32api.GetTempFileName anyways
# debug options
debug = 0 # 1 or 0
if debug:
fxn = 'glm' # 'glm' , 'cart' or 'gam'
prefix = 'D:/projects/ArcRstats/'
in_obs = prefix + 'sp_obs.shp'
in_rnd = prefix + 'sp_rnd.shp'
in_rnames = ['dem', 'aspect', 'tci', 'landcov']
sep = ';' + prefix
in_rasters = prefix + sep.join(in_rnames)
out_mdl = prefix + 'out_' + fxn
out_tbl_obs = out_mdl + '_smpl_obs.dbf'
out_tbl_rnd = out_mdl + '_smpl_rnd.dbf'
class RModel:
def __init__(self):
pass
def msg(self, msg):
# utility message function
self.gp.AddMessage(msg) # print to geoprocessor
print msg # print to console
self.rlog.write('# %s\n' % msg) # append to log file
def rcmd(self, cmd):
# utility R command function
try:
self.r.EvaluateNoReturn(cmd) # run command
except:
self.msg('Unexpected error with R command...\n' + str(cmd) + '\n' + str(self.r.GetErrorText()) + '\n' + str(sys.exc_info()[0]))
raise
#sys.exit()
self.rlog.write(cmd+'\n') # append to log file
def initialize(self):
# initialization calls
# get input variables
global fxn
self.fxn = fxn # input, function to use in modeling
# comment below to debug
if debug:
global in_obs, in_rnd, in_rasters, out_mdl, out_tbl_obs, out_tbl_rnd
self.in_obs = in_obs
self.in_rnd = in_rnd
self.in_rasters = in_rasters
self.out_mdl = out_mdl
self.out_tbl_obs = out_tbl_obs
self.out_tbl_rnd = out_tbl_rnd
else:
for i in range(0,len(sys.argv)):
if isinstance(sys.argv[i],str):
sys.argv[i] = sys.argv[i].replace('\\','/')
self.in_obs = sys.argv[2] # input, observed points featureclass
self.in_rnd = sys.argv[3] # input, random points featureclass
self.in_rasters = sys.argv[4] # input, multiple rasters
## self.out_mdl = os.path.dirname(sys.argv[5]) + '/' + os.path.basename(sys.argv[5]) # output modeled raster
## self.out_tbl_obs = os.path.dirname(sys.argv[6]) + '/' + os.path.basename(sys.argv[6]) # output sampled obs dbf
## self.out_tbl_rnd = os.path.dirname(sys.argv[7]) + '/' + os.path.basename(sys.argv[7]) # output sampled rnd dbf
self.out_mdl = sys.argv[5] # output modeled raster
self.out_tbl_obs = sys.argv[6] # output sampled obs dbf
self.out_tbl_rnd = sys.argv[7] # output sampled rnd dbf
# assign other output filenames
self.cwd = os.path.dirname(self.out_mdl)
self.samplesfile = self.out_mdl + '_samples.txt'
self.rlogfile = self.out_mdl + '_log.r'
# open r_log
self.rlog = open(self.rlogfile, 'w')
self.rlog.write('# ' + self.fxn.upper() + ' started on ' + time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) + '\n')
# initialize geoprocessor
self.gp = Dispatch("esriGeoprocessing.GpDispatch.1")
self.gp.CheckOutExtension("Spatial")
self.gp.OverwriteOutput = 1 # setup for overwrite
# initialize R stats
self.r = Dispatch("StatConnectorSrv.StatConnector")
self.r.Init("R")
# setup dictionary list variables
self.msg(' setup variables...')
self.rasters = {} # dictionary of raster paths by raster name
self.samples = {} # dictionary of sample value lists by raster name
self.samples['obs'] = [] # known response sample value list
for path in self.in_rasters.split(';'):
path = path.replace("'","");
name = os.path.basename(path)
self.rasters[name] = path
self.samples[name] = []
def sample2r(self):
self.msg(' sample rasters...')
# sample across rasters for observed and random locations
try:
self.gp.Sample_sa(';'.join(self.rasters.values()), self.in_obs, self.out_tbl_obs, 'NEAREST')
self.gp.Sample_sa(';'.join(self.rasters.values()), self.in_rnd, self.out_tbl_rnd, 'NEAREST')
except:
print 'ERROR: ' + self.gp.GetMessages()
# read in sampled presence (observation) tables
self.msg(' read in sampled presence tables...')
rows = self.gp.SearchCursor(self.out_tbl_obs)
row = rows.Next()
while row:
self.samples['obs'].append('present') # set to 1 for obs, 0 for rnd
for col in self.rasters.keys(): # iterate through sampled columns
self.samples[col].append(row.GetValue(col))
row = rows.Next() # advance to next row
# read in sampled absence (random) tables
self.msg(' read in sampled absence/random tables...')
rows = self.gp.SearchCursor(self.out_tbl_rnd)
row = rows.Next()
while row:
self.samples['obs'].append('absent') # set to 1 for obs, 0 for rnd
for col in self.rasters.keys(): # iterate through sampled columns
self.samples[col].append(row.GetValue(col))
row = rows.Next() # advance to next row
# write out samplesfile.txt
f=open(self.samplesfile, 'w')
for i in range(len(self.samples['obs'])):
rowdata = []
for k in self.samples.keys():
if i == 0: # header row
rowdata.append(str(k))
else:
v = str(self.samples[k][i])
rowdata.append(v)
sep = ','
f.write(sep.join(rowdata) + '\n')
f.close()
# read into R
#self.rcmd('dat <- read.table("' + self.samplesfile.replace('\\','/') + '", header=TRUE, sep = ",", na.strings = "-9999.0")')
self.rcmd('dat <- read.table("' + self.samplesfile + '", header=TRUE, sep = ",", na.strings = "-9999.0")')
del(self.samples) # clean up python memory
def grids2r(self):
# feed grid data to R
self.msg(' feed grid data to R for predicting with model...')
# find grid with largest cellsize
cellwidth = 0
self.cellsizes = {}
self.extents = {}
self.sprefs = {}
for n,p in self.rasters.items():
descr = self.gp.Describe(p)
self.cellsizes[n] = str(descr.MeanCellWidth)
self.extents[n] = str(descr.Extent)
self.sprefs[n] = descr.SpatialReference
if descr.MeanCellWidth > cellwidth:
# assign as template raster
self.template = n
self.msg(' template grid with largest cell size: ' + n)
# set environment based on cellraster
self.gp.Workspace = self.cwd
self.gp.OutputCoordinateSystem = self.sprefs[self.template]
self.gp.Extent = self.extents[self.template] # snap grid
self.msg(' resample other grids, if different cellsize/extent from template...')
# resample and size, if necessary
for n,p in self.rasters.items():
if self.cellsizes[n] <> self.cellsizes[self.template] or self.extents[n] <> self.extents[self.template]:
try:
if self.gp.Exists(p + '_r'):
self.gp.Delete(p + '_r')
self.gp.Resample(p, p + '_r', self.cellsizes[self.template], 'NEAREST')
#gp.Clip(p + '_r', cellextent, p + '_c')
except:
print self.gp.GetMessages()
# assign resampled/resized raster path to rasters dictionary
self.rasters[n] = p+'_r'
# output to ascii, read into R
self.msg(' output grids to temporary ASCII files and read into R...')
self.rasters_asc = self.rasters.copy()
for n,p in self.rasters.items():
# output to ascii
p_asc = p + '.asc'
self.rasters_asc[n] = p_asc
try:
self.gp.RasterToASCII_conversion(p, p_asc)
except:
self.msg(self.gp.GetMessages())
# read ascii table into R as a vector for model prediction
self.rcmd(n + ' <- read.table("' + self.rasters_asc[n].replace('\\','/') + '", sep=" ", na.strings="-9999", skip=6)')
self.rcmd(n + ' <- as.vector(data.matrix(' + n + '[-length(' + n + ')]))') # exclude trailing column created by extra space in RasterToASCII output
# get header information from template for outputting model prediction from R to ASCII ArcGIS Raster format
self.header = {}
if n == self.template:
# read in header info
f=open(self.rasters_asc[n], 'r')
self.header['ncols'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['nrows'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['xllcorner'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['yllcorner'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['cellsize'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['NODATA_value'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
f.close()
# write out header info to output model grid ascii file
self.out_mdl_ascii = self.out_mdl + '.asc'
f=open(self.out_mdl_ascii, 'w')
for k, v in self.header.items():
f.write('%s %s\n' % (k, v))
f.close()
# bind to data frame in R
sep = ', '
self.rcmd('datpred <- data.frame(cbind(' + sep.join(self.rasters.keys()) + '))')
# clear old variables from R session memory
for n in self.rasters.keys():
self.rcmd('rm('+n+')')
def pred2gis(self):
# expects a predict object named 'pred' in R
self.msg(' convert model prediction to grid...')
self.rcmd('write.table(pred, file="' + self.out_mdl_ascii.replace('\\','/') + '", append=TRUE, sep=" ", col.names=FALSE, row.names=FALSE, na="-9999")')
try:
if self.gp.Exists(self.out_mdl):
self.gp.Delete(self.out_mdl)
self.gp.ASCIIToRaster_conversion(self.out_mdl_ascii, self.out_mdl, "FLOAT")
self.gp.Toolbox = "Management"
# this should work, but the SpatialReference returns an object, not the expected *.prj file DefineProjection wants
#self.gp.DefineProjection(self.out_mdl, self.sprefs[template])
except:
print self.gp.GetMessages()
# project model raster by copying prj.adf
prj = self.rasters[self.template] + '/prj.adf'
if os.path.exists(prj):
shutil.copyfile(prj, self.out_mdl + '/prj.adf')
def plotsamples(self):
self.rcmd('plotpre <- "' + self.out_mdl.replace('\\','/') + '"')
self.rcmd('datenv <- dat[,names(dat)!="obs"]')
self.rcmd('png(paste(sep='', plotpre, "_plotpairs.png"))')
self.rcmd('pairs(datenv, main="Correlations Between Variables")')
self.rcmd('dev.off()')
self.rcmd('''for (c in names(datenv)){
denspres <- density(na.exclude(dat[dat[["obs"]]==1, c]))
densabs <- density(na.exclude(dat[dat[["obs"]]==0, c]))
xlim <- range(na.exclude(dat[, c]))
ylim <- c(0,max(c(denspres$y, densabs$y)))
#png(filename=filename, width=600, height=400, pointsize=1, bg="white", res=200)
png(paste(sep='', plotpre, '_hist_', c, '.png'))
plot(denspres, type='l', main=paste(c,'Distribution'), xlab=c, ylab='Density', ylim=ylim, xlim=xlim)
lines(densabs, lty=2)
legend(x=xlim[1], y=ylim[2], legend=c('presence', 'absence'), lty=1:2)
dev.off()
}''')
def finalize(self):
# clean up temp files
## if not debug:
## for n,p in self.rasters_asc.items():
## os.unlink(p)
# close r
self.r.Close()
self.rlog.close()
# close gp
del(self.gp)
class GLM(RModel):
def __init__(self):
# initialize
self.initialize()
# sample data
self.sample2r()
self.plotsamples()
# build model
self.msg(' generate GLM in R...')
self.rcmd('dat$obs <- factor(dat$obs)')
self.rcmd('dat <- na.exclude(dat)')
self.rcmd('mdlall <- glm(obs ~ ., data=dat, family=binomial(link="logit"))')
self.msg(' find best GLM model by AIC...')
self.rcmd('library(MASS)')
self.rcmd('mdl <- stepAIC(mdlall, trace=F)')
# save model summaries
self.rcmd('sink("' + self.out_mdl.replace('\\','/') + '_summary.txt")')
self.rcmd('cat("\nGLM all..\n\n")')
self.rcmd('print(summary(mdlall))')
self.rcmd('cat("\nGLM best model, with step-wise AIC selection of coefficients...\n\n")')
self.rcmd('print(summary(mdl))')
self.rcmd('sink()')
# grid data
self.grids2r()
# predict with model
self.msg(' predict GLM in R...')
#self.rcmd('rowsna <- sort(unique(which(is.na(datpred), arr.ind=TRUE)[,1]))')
#self.rcmd('datpred <- na.exclude(datpred)')
self.rcmd('pred <- predict(mdl, newdata=datpred, na.action=na.pass, type="response")')
#self.rcmd('''for (row in rowsna){
# pred <- append(pred, NA, row-1)
# }''')
self.rcmd('dim(pred) <- c(' + self.header['nrows'] + ', ' + self.header['ncols'] + ')')
# save model and data
self.rcmd('save(dat, mdlall, mdl, datpred, pred, file = "' + self.out_mdl.replace('\\','/') + '.rdata")')
# prediction to grid
self.pred2gis()
self.finalize()
class GLM2(RModel):
def __init__(self):
# initialize
self.initialize()
# sample data
self.sample2r()
## self.plotsamples()
# build model
self.msg(' generate GLM in R...')
self.rcmd('dat$obs <- factor(dat$obs)')
self.rcmd('dat <- na.exclude(dat)')
self.rcmd('mdlall <- glm(obs ~ ., data=dat, family=binomial(link="logit"))')
self.msg(' find best GLM model by AIC...')
self.rcmd('library(MASS)')
self.rcmd('mdl <- stepAIC(mdlall, trace=F)')
# save model summaries
#self.rcmd('sink("' + self.out_mdl.replace('\\','/') + '_summary.txt")')
self.rcmd('sink("' + self.out_mdl + '_summary.txt")')
self.rcmd('cat("\nGLM all..\n\n")')
self.rcmd('print(summary(mdlall))')
self.rcmd('cat("\nGLM best model, with step-wise AIC selection of coefficients...\n\n")')
self.rcmd('print(summary(mdl))')
self.rcmd('sink()')
# grid data
#self.grids2r() # skipping
# predict with model
self.msg(' extract GLM coefficients from R...')
coeffs = {}
coeffs_d = self.r.Evaluate('summary(mdl)$coefficients')
coeffs_r = self.r.Evaluate('rownames(summary(mdl)$coefficients)')
coeffs_c = self.r.Evaluate('colnames(summary(mdl)$coefficients)')
for i in range(0, len(coeffs_r)):
coeffs[coeffs_r[i]] = dict([(coeffs_c[j], coeffs_d[i][j]) for j in range(0, len(coeffs_c))])
# formulate expression for map algebra
in_rasters = []; expression = []
for r in coeffs.keys():
if r=='(Intercept)':
expression.append(str(coeffs[r]['Estimate']))
else:
expression.append('(' + str(coeffs[r]['Estimate']) + ' * ' + self.rasters[r] + ')')
in_expression = ' + '.join(expression)
try:
self.gp.SingleOutputMapAlgebra_sa(in_expression, self.out_mdl)
except:
print 'ERROR: ' + self.gp.GetMessages()
# save model and data
self.rcmd('save(file="' + self.out_mdl + '.rdata")')
# prediction to grid
#self.pred2gis()
#self.finalize()
class GAM(RModel):
def __init__(self):
# initialize
self.initialize()
# sample data
self.sample2r()
self.plotsamples()
# construct formula
self.msg(' generate GAM formula...')
terms = []
for k in self.rasters.keys():
terms.append('s(' + k + ', bs="ts")')
sep = ' + '
formula = 'obs ~ ' + sep.join(terms)
# build model
self.msg(' generate GAM in R...')
self.rcmd('dat$obs <- factor(dat$obs)')
self.rcmd('library(mgcv)')
self.rcmd('mdl <- gam(' + formula + ', data=dat, family=binomial(link="logit"))')
# save model summary and graphics
self.rcmd('sink("' + self.out_mdl.replace('\\','/') + '_summary.txt")')
self.rcmd('cat("\nGAM..\n\n")')
self.rcmd('print(summary(mdl))')
self.rcmd('sink()')
self.rcmd('png("' + self.out_mdl.replace('\\','/') + '_plot.png")')
self.rcmd('plot(mdl,pages=1,residuals=TRUE,all.terms=TRUE,shade=TRUE,shade.col="gray")')
self.rcmd('dev.off()')
# grid data
self.grids2r()
# predict with model
self.msg(' predict with GAM in R...')
self.rcmd('rowsna <- sort(unique(which(is.na(datpred), arr.ind=TRUE)[,1]))')
self.rcmd('datpred <- na.exclude(datpred)')
self.rcmd('pred <- predict(mdl, newdata=datpred, type="response", block.size=0.5, newdata.guaranteed=FALSE)')
self.rcmd('''for (row in rowsna){
pred <- append(pred, NA, row-1)
}''')
self.rcmd('dim(pred) <- c(' + self.header['nrows'] + ', ' + self.header['ncols'] + ')')
# save model and data
self.rcmd('save(dat, mdl, datpred, pred, file = "' + self.out_mdl.replace('\\','/') + '.rdata")')
# prediction to grid
self.pred2gis()
self.finalize()
class CART(RModel):
def __init__(self):
# initialize
self.initialize()
# sample data
self.sample2r()
self.plotsamples()
# build model
self.msg(' generate CART in R...')
self.rcmd('dat$obs <- factor(dat$obs)')
self.rcmd('library(rpart)')
self.rcmd('mdlall <- rpart(obs ~ ., data=dat, control=rpart.control(cp=0), method="class")')
self.rcmd('mdlall.cp <- mdlall$cptable[mdlall$cptable[,4] == min(mdlall$cptable[,4]), 1]')
self.msg(' trim CART (complexity parameter with minimum cross-validation error)...')
self.rcmd('mdl <- rpart(obs ~ ., data=dat, control=rpart.control(cp=mdlall.cp), na.action=na.pass, method="class")')
# save model summary and graphics
self.msg(' plot CART tree from R...')
self.rcmd('png("' + self.out_mdl.replace('\\','/') + '_tree.png")')
self.rcmd('plot(mdl)')
self.rcmd('text(mdl, use.n=TRUE)')
self.rcmd('dev.off()')
self.rcmd('sink("' + self.out_mdl.replace('\\','/') + '_summary.txt")')
self.rcmd('cat("\nFull CART (cp=0)...\n\n")')
self.rcmd('print(summary(mdlall))')
self.rcmd('cat("\n\nModified CART (using",str(mdlall.cp),"as complexity parameter from Full CART)...\n\n")')
self.rcmd('print(summary(mdl))')
self.rcmd('sink()')
# grid data
self.grids2r()
# predict with model
self.msg(' predict CART in R...')
self.rcmd('pred <- predict(mdl, newdata=datpred, na.action=na.pass, type="prob")[,2]') # the probability of it being the second answer ( = 1 = presence)
self.rcmd('dim(pred) <- c(' + self.header['nrows'] + ', ' + self.header['ncols'] + ')')
# save model and data
self.rcmd('save(dat, mdl, datpred, pred, file = "' + self.out_mdl.replace('\\','/') + '.rdata")')
# prediction to grid
self.pred2gis()
self.finalize()
class CART2(RModel):
def __init__(self):
# initialize
self.initialize()
# sample data
## self.sample2r()
self.rcmd('dat <- read.table("' + self.samplesfile + '", header=TRUE, sep = ",", na.strings = "-9999.0")')
## self.plotsamples()
## # build model
## self.msg(' generate CART in R...')
## self.rcmd('dat$obs <- factor(dat$obs)')
## self.rcmd('library(rpart)')
## self.rcmd('mdlall <- rpart(obs ~ ., data=dat, control=rpart.control(cp=0), method="class")')
## self.rcmd('mdlall.cp <- mdlall$cptable[mdlall$cptable[,4] == min(mdlall$cptable[,4]), 1]')
## self.msg(' trim CART (complexity parameter with minimum cross-validation error)...')
## self.rcmd('mdl <- rpart(obs ~ ., data=dat, control=rpart.control(cp=mdlall.cp), na.action=na.pass, method="class")')
##
## # save model summary and graphics
## self.msg(' plot CART tree from R...')
## self.rcmd('png("' + self.out_mdl.replace('\\','/') + '_tree.png")')
## self.rcmd('plot(mdl, margin=.05)')
## self.rcmd('text(mdl, use.n=TRUE, cex=.6)')
## self.rcmd('dev.off()')
## self.rcmd('sink("' + self.out_mdl + '_summary.txt")')
## self.rcmd('cat("\nFull CART (cp=0)...\n\n")')
## self.rcmd('print(summary(mdlall))')
## self.rcmd('cat("\n\nModified CART (using",str(mdlall.cp),"as complexity parameter from Full CART)...\n\n")')
## self.rcmd('print(summary(mdl))')
## self.rcmd('sink()')
# build model
#self.gp.Workspace = r'M:\projects\ArcRstats\ArcRstats\example\data'
self.msg(' generate CART in R...')
self.rcmd('library(rpart)')
self.rcmd('mdl <- rpart(obs ~ ., data=dat, method="class")')
self.rcmd('inodes = rownames(mdl$frame[mdl$frame$var=="<leaf>",])')
self.rcmd('lnodes = length(inodes)')
self.rcmd('paths = path.rpart(mdl, inodes, print.it=F)')
self.rcmd('formulas = character(lnodes)')
self.r.SetSymbol('raster.names',self.rasters.keys())
self.r.SetSymbol('raster.paths',self.rasters.values())
self.rcmd('''for (i in 1:lnodes){
ps = paths[[i]][-1]
for (j in 1:length(ps)){
for (k in 1:length(raster.names)){
ps[j] = sub(raster.names[k],raster.paths[k], ps[j])
}
}
formulas[i] = paste(ps, collapse=" & ")
}''')
formulas = self.r.Evaluate('formulas')
algebra = ''
for i in range(0,len(formulas)):
f = formulas[i]
algebra += 'con(' + f + ',' + str(i+1) + ','
algebra += '0' + ')'*len(formulas)
try:
self.gp.SingleOutputMapAlgebra_sa(algebra, self.out_mdl)
except:
print 'ERROR: ' + self.gp.GetMessages()
## # grid data
## self.grids2r()
##
## # predict with model
## self.msg(' predict CART in R...')
## self.rcmd('pred <- predict(mdl, newdata=datpred, na.action=na.pass, type="prob")[,2]') # the probability of it being the second answer ( = 1 = presence)
## self.rcmd('dim(pred) <- c(' + self.header['nrows'] + ', ' + self.header['ncols'] + ')')
## # save model and data
## self.rcmd('save(file="' + self.out_mdl + '.rdata")')
## # prediction to grid
## self.pred2gis()
## self.finalize()
if __name__ == "__main__":
# main call
if not debug:
fxn = sys.argv[1] # function switch as first argument
if fxn == 'glm':
GLM()
elif fxn == 'glm2':
GLM2()
elif fxn == 'gam':
GAM()
elif fxn == 'cart':
CART()
elif fxn == 'cart2':
CART2()
|
ArcRstats
|
/ArcRstats-0.8.alpha.zip/ArcRstats-0.8.alpha/arc_r/multivariate_regression.py
|
multivariate_regression.py
|
from win32com.client import Dispatch
import os, sys, re, time, shutil # removed: tempfile, preferable to use win32api.GetTempFileName anyways
from win32api import GetShortPathName
# debug options
debug = 0 # 1 or 0
if debug:
fxn = 'glm' # 'glm' , 'cart' or 'gam'
prefix = 'D:/projects/ArcRstats/'
in_obs = prefix + 'sp_obs.shp'
in_rnd = prefix + 'sp_rnd.shp'
in_rnames = ['dem', 'aspect', 'tci', 'landcov']
sep = ';' + prefix
in_rasters = prefix + sep.join(in_rnames)
out_mdl = prefix + 'out_' + fxn
out_dbf_obs = out_mdl + '_smpl_obs.dbf'
out_dbf_rnd = out_mdl + '_smpl_rnd.dbf'
class RModel:
def __init__(self):
pass
def msg(self, msg):
# utility message function
self.gp.AddMessage(msg) # print to geoprocessor
print msg # print to console
self.rlog.write('# %s\n' % msg) # append to log file
def rcmd(self, cmd):
# utility R command function
try:
self.r.EvaluateNoReturn(cmd) # run command
except:
self.msg('Unexpected error with R command...\n' + str(cmd) + '\n' + str(self.r.GetErrorText()) + '\n' + str(sys.exc_info()[0]))
raise
#sys.exit()
self.rlog.write(cmd+'\n') # append to log file
def initialize(self):
# initialization calls
# get input variables
global fxn
self.fxn = fxn # input, function to use in modeling
# comment below to debug
if debug:
global in_obs, in_rnd, in_rasters, out_mdl, out_dbf_obs, out_dbf_rnd
self.in_obs = in_obs
self.in_rnd = in_rnd
self.in_rasters = in_rasters
self.out_mdl = out_mdl
self.out_dbf_obs = out_dbf_obs
self.out_dbf_rnd = out_dbf_rnd
else:
self.in_obs = GetShortPathName(sys.argv[2]) # input, observed points featureclass
self.in_rnd = GetShortPathName(sys.argv[3]) # input, random points featureclass
self.in_rasters = sys.argv[4] # input, multiple rasters
self.out_mdl = GetShortPathName(os.path.dirname(sys.argv[5])) + '/' + os.path.basename(sys.argv[5]) # output modeled raster
self.out_dbf_obs = GetShortPathName(os.path.dirname(sys.argv[6])) + '/' + os.path.basename(sys.argv[6]) # output sampled obs dbf
self.out_dbf_rnd = GetShortPathName(os.path.dirname(sys.argv[7])) + '/' + os.path.basename(sys.argv[7]) # output sampled rnd dbf
# assign other output filenames
self.cwd = GetShortPathName(os.path.dirname(self.out_mdl))
self.samplesfile = self.out_mdl + '_samples.txt'
self.rlogfile = self.out_mdl + '_log.r'
# open r_log
self.rlog = open(self.rlogfile, 'w')
self.rlog.write('# ' + self.fxn.upper() + ' started on ' + time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) + '\n')
# initialize geoprocessor
self.gp = Dispatch("esriGeoprocessing.GpDispatch.1")
self.gp.CheckOutExtension("Spatial")
# initialize R stats
self.r = Dispatch("StatConnectorSrv.StatConnector")
self.r.Init("R")
# setup dictionary list variables
self.msg(' setup variables...')
self.rasters = {} # dictionary of raster paths by raster name
self.samples = {} # dictionary of sample value lists by raster name
self.samples['obs'] = [] # known response sample value list
for path in self.in_rasters.split(';'):
path = path.replace("'","");
name = os.path.basename(path)
self.rasters[name] = GetShortPathName(path)
self.samples[name] = []
def sample2r(self):
self.msg(' sample rasters...')
# check if integer rasters b/c of SAMPLE bug in ArcGIS 9 (supposedly fixed in 9.1)
self.rasters_int = self.rasters.copy()
for name, path in self.rasters.items():
desc = self.gp.Describe(path)
if not desc.IsInteger:
path_int = path+'_i'
self.msg(' raster %s being converted to integer (b/c ArcGIS SAMPLE bug)' % name)
try:
if self.gp.Exists(path_int):
self.gp.Delete(path_int)
self.gp.MultiOutputMapAlgebra_sa(path_int + ' = INT(' + path + ' * 1000)') # multiply 1000
except:
self.msg(gp.GetMessages())
self.rasters_int[name] = path_int
sep = ';'
self.rasters_intstr = sep.join(self.rasters_int.values())
# initialize geoprocessor
del self.gp
self.gp = Dispatch("esriGeoprocessing.GpDispatch.1")
self.gp.CheckOutExtension("Spatial")
# sample across rasters for observed and random locations
if os.path.exists(self.out_dbf_obs):
os.unlink(self.out_dbf_obs)
if os.path.exists(self.out_dbf_rnd):
os.unlink(self.out_dbf_rnd)
try:
self.gp.Sample_sa(self.rasters_intstr, self.in_obs, self.out_dbf_obs, 'NEAREST')
self.gp.Sample_sa(self.rasters_intstr, self.in_rnd, self.out_dbf_rnd, 'NEAREST')
except:
print 'ERROR: ' + self.gp.GetMessages()
# read in sampled presence (observation) tables
self.msg(' read in sampled tables...')
rows = self.gp.SearchCursor(self.out_dbf_obs)
row = rows.Next()
while row:
self.samples['obs'].append(1) # set to 1 for obs, 0 for rnd
for col in self.rasters.keys(): # iterate through sampled columns
# correct for integer conversion b/c of SAMPLE bug in ArcGIS 9 (supposedly fixed in 9.1)
if self.rasters[col] == self.rasters_int[col]:
val = row.GetValue(col)
else:
col_int = os.path.basename(self.rasters_int[col])
val = row.GetValue(col_int) / 1000 # divide 1000
self.samples[col].append(val)
row = rows.Next() # advance to next row
# read in sampled absence (random) tables
rows = self.gp.SearchCursor(self.out_dbf_rnd)
row = rows.Next()
while row:
self.samples['obs'].append(0) # set to 1 for obs, 0 for rnd
for col in self.rasters.keys(): # iterate through sampled columns
# correct for integer conversion b/c of SAMPLE bug in ArcGIS 9 (supposedly fixed in 9.1)
if self.rasters[col] == self.rasters_int[col]:
val = row.GetValue(col)
else:
col_int = os.path.basename(self.rasters_int[col])
val = row.GetValue(col_int) / 1000 # divide 1000
self.samples[col].append(val)
row = rows.Next() # advance to next row
# write out samplesfile.txt
f=open(self.samplesfile, 'w')
for i in range(len(self.samples['obs'])):
rowdata = []
for k in self.samples.keys():
if i == 0: # header row
rowdata.append(str(k))
else:
v = str(self.samples[k][i])
rowdata.append(v)
sep = ','
f.write(sep.join(rowdata) + '\n')
f.close()
# read into R
self.rcmd('dat <- read.table("' + self.samplesfile.replace('\\','/') + '", header=TRUE, sep = ",", na.strings = "-9999.0")')
del(self.samples) # clean up python memory
def grids2r(self):
# feed grid data to R
self.msg(' feed grid data to R for predicting with model...')
# find grid with largest cellsize
cellwidth = 0
self.cellsizes = {}
self.extents = {}
self.sprefs = {}
for n,p in self.rasters.items():
descr = self.gp.Describe(p)
self.cellsizes[n] = str(descr.MeanCellWidth)
self.extents[n] = str(descr.Extent)
self.sprefs[n] = descr.SpatialReference
if descr.MeanCellWidth > cellwidth:
# assign as template raster
self.template = n
self.msg(' template grid with largest cell size: ' + n)
# set environment based on cellraster
self.gp.Workspace = self.cwd
self.gp.OutputCoordinateSystem = self.sprefs[self.template]
self.gp.Extent = self.extents[self.template] # snap grid
self.msg(' resample other grids, if different cellsize/extent from template...')
# resample and size, if necessary
for n,p in self.rasters.items():
if self.cellsizes[n] <> self.cellsizes[self.template] or self.extents[n] <> self.extents[self.template]:
try:
if self.gp.Exists(p + '_r'):
self.gp.Delete(p + '_r')
self.gp.Resample(p, p + '_r', self.cellsizes[self.template], 'NEAREST')
#gp.Clip(p + '_r', cellextent, p + '_c')
except:
print self.gp.GetMessages()
# assign resampled/resized raster path to rasters dictionary
self.rasters[n] = p+'_r'
# output to ascii, read into R
self.msg(' output grids to temporary ASCII files and read into R...')
self.rasters_asc = self.rasters.copy()
for n,p in self.rasters.items():
# get temporary ascii output name
#self.rasters_asc[n] = tempfile.mktemp('.asc').replace('\\','/')
p_asc = p + '.asc'
self.rasters_asc[n] = p_asc
if os.path.exists(p_asc):
os.unlink(p_asc)
try:
self.gp.RasterToASCII_conversion(p, p_asc)
except:
self.msg(self.gp.GetMessages())
# read ascii table into R as a vector for model prediction
self.rcmd(n + ' <- read.table("' + self.rasters_asc[n].replace('\\','/') + '", sep=" ", na.strings="-9999", skip=6)')
self.rcmd(n + ' <- as.vector(data.matrix(' + n + '[-length(' + n + ')]))') # exclude trailing column created by extra space in RasterToASCII output
# get header information from template for outputting model prediction from R to ASCII ArcGIS Raster format
self.header = {}
if n == self.template:
# read in header info
f=open(self.rasters_asc[n], 'r')
self.header['ncols'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['nrows'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['xllcorner'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['yllcorner'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['cellsize'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
self.header['NODATA_value'] = re.match('([\S]+)\s+([\S]+)', f.readline()).groups()[1]
f.close()
# write out header info to output model grid ascii file
self.out_mdl_ascii = self.out_mdl + '.asc'
f=open(self.out_mdl_ascii, 'w')
for k, v in self.header.items():
f.write('%s %s\n' % (k, v))
f.close()
# bind to data frame in R
sep = ', '
self.rcmd('datpred <- data.frame(cbind(' + sep.join(self.rasters.keys()) + '))')
# clear old variables from R session memory
for n in self.rasters.keys():
self.rcmd('rm('+n+')')
def pred2gis(self):
# expects a predict object named 'pred' in R
self.msg(' convert model prediction to grid...')
self.rcmd('write.table(pred, file="' + self.out_mdl_ascii.replace('\\','/') + '", append=TRUE, sep=" ", col.names=FALSE, row.names=FALSE, na="-9999")')
try:
if self.gp.Exists(self.out_mdl):
self.gp.Delete(self.out_mdl)
self.gp.ASCIIToRaster_conversion(self.out_mdl_ascii, self.out_mdl, "FLOAT")
self.gp.Toolbox = "Management"
# this should work, but the SpatialReference returns an object, not the expected *.prj file DefineProjection wants
#self.gp.DefineProjection(self.out_mdl, self.sprefs[template])
except:
print self.gp.GetMessages()
# project model raster by copying prj.adf
prj = self.rasters[self.template] + '/prj.adf'
if os.path.exists(prj):
shutil.copyfile(prj, self.out_mdl + '/prj.adf')
def plotsamples(self):
self.rcmd('plotpre <- "' + self.out_mdl.replace('\\','/') + '"')
self.rcmd('datenv <- dat[,names(dat)!="obs"]')
self.rcmd('png(paste(sep='', plotpre, "_plotpairs.png"))')
self.rcmd('pairs(datenv, main="Correlations Between Variables")')
self.rcmd('dev.off()')
self.rcmd('''for (c in names(datenv)){
denspres <- density(na.exclude(dat[dat[["obs"]]==1, c]))
densabs <- density(na.exclude(dat[dat[["obs"]]==0, c]))
xlim <- range(na.exclude(dat[, c]))
ylim <- c(0,max(c(denspres$y, densabs$y)))
#png(filename=filename, width=600, height=400, pointsize=1, bg="white", res=200)
png(paste(sep='', plotpre, '_hist_', c, '.png'))
plot(denspres, type='l', main=paste(c,'Distribution'), xlab=c, ylab='Density', ylim=ylim, xlim=xlim)
lines(densabs, lty=2)
legend(x=xlim[1], y=ylim[2], legend=c('presence', 'absence'), lty=1:2)
dev.off()
}''')
def finalize(self):
# clean up temp files
## if not debug:
## for n,p in self.rasters_asc.items():
## os.unlink(p)
# close r
self.r.Close()
self.rlog.close()
# close gp
del(self.gp)
class GLM(RModel):
def __init__(self):
# initialize
self.initialize()
# sample data
self.sample2r()
self.plotsamples()
# build model
self.msg(' generate GLM in R...')
self.rcmd('dat$obs <- factor(dat$obs)')
self.rcmd('dat <- na.exclude(dat)')
self.rcmd('mdlall <- glm(obs ~ ., data=dat, family=binomial(link="logit"))')
self.msg(' find best GLM model by AIC...')
self.rcmd('library(MASS)')
self.rcmd('mdl <- stepAIC(mdlall, trace=F)')
# save model summaries
self.rcmd('sink("' + self.out_mdl.replace('\\','/') + '_summary.txt")')
self.rcmd('cat("\nGLM all..\n\n")')
self.rcmd('print(summary(mdlall))')
self.rcmd('cat("\nGLM best model, with step-wise AIC selection of coefficients...\n\n")')
self.rcmd('print(summary(mdl))')
self.rcmd('sink()')
# grid data
self.grids2r()
# predict with model
self.msg(' predict GLM in R...')
#self.rcmd('rowsna <- sort(unique(which(is.na(datpred), arr.ind=TRUE)[,1]))')
#self.rcmd('datpred <- na.exclude(datpred)')
self.rcmd('pred <- predict(mdl, newdata=datpred, na.action=na.pass, type="response")')
#self.rcmd('''for (row in rowsna){
# pred <- append(pred, NA, row-1)
# }''')
self.rcmd('dim(pred) <- c(' + self.header['nrows'] + ', ' + self.header['ncols'] + ')')
# save model and data
self.rcmd('save(dat, mdlall, mdl, datpred, pred, file = "' + self.out_mdl.replace('\\','/') + '.rdata")')
# prediction to grid
self.pred2gis()
self.finalize()
class GAM(RModel):
def __init__(self):
# initialize
self.initialize()
# sample data
self.sample2r()
self.plotsamples()
# construct formula
self.msg(' generate GAM formula...')
terms = []
for k in self.rasters.keys():
terms.append('s(' + k + ', bs="ts")')
sep = ' + '
formula = 'obs ~ ' + sep.join(terms)
# build model
self.msg(' generate GAM in R...')
self.rcmd('dat$obs <- factor(dat$obs)')
self.rcmd('library(mgcv)')
self.rcmd('mdl <- gam(' + formula + ', data=dat, family=binomial(link="logit"))')
# save model summary and graphics
self.rcmd('sink("' + self.out_mdl.replace('\\','/') + '_summary.txt")')
self.rcmd('cat("\nGAM..\n\n")')
self.rcmd('print(summary(mdl))')
self.rcmd('sink()')
self.rcmd('png("' + self.out_mdl.replace('\\','/') + '_plot.png")')
self.rcmd('plot(mdl,pages=1,residuals=TRUE,all.terms=TRUE,shade=TRUE,shade.col="gray")')
self.rcmd('dev.off()')
# grid data
self.grids2r()
# predict with model
self.msg(' predict with GAM in R...')
self.rcmd('rowsna <- sort(unique(which(is.na(datpred), arr.ind=TRUE)[,1]))')
self.rcmd('datpred <- na.exclude(datpred)')
self.rcmd('pred <- predict(mdl, newdata=datpred, type="response", block.size=0.5, newdata.guaranteed=FALSE)')
self.rcmd('''for (row in rowsna){
pred <- append(pred, NA, row-1)
}''')
self.rcmd('dim(pred) <- c(' + self.header['nrows'] + ', ' + self.header['ncols'] + ')')
# save model and data
self.rcmd('save(dat, mdl, datpred, pred, file = "' + self.out_mdl.replace('\\','/') + '.rdata")')
# prediction to grid
self.pred2gis()
self.finalize()
class CART(RModel):
def __init__(self):
# initialize
self.initialize()
# sample data
self.sample2r()
self.plotsamples()
# build model
self.msg(' generate CART in R...')
self.rcmd('dat$obs <- factor(dat$obs)')
self.rcmd('library(rpart)')
self.rcmd('mdlall <- rpart(obs ~ ., data=dat, control=rpart.control(cp=0), method="class")')
self.rcmd('mdlall.cp <- mdlall$cptable[mdlall$cptable[,4] == min(mdlall$cptable[,4]), 1]')
self.msg(' trim CART (complexity parameter with minimum cross-validation error)...')
self.rcmd('mdl <- rpart(obs ~ ., data=dat, control=rpart.control(cp=mdlall.cp), na.action=na.pass, method="class")')
# save model summary and graphics
self.msg(' plot CART tree from R...')
self.rcmd('png("' + self.out_mdl.replace('\\','/') + '_tree.png")')
self.rcmd('plot(mdl)')
self.rcmd('text(mdl, use.n=TRUE)')
self.rcmd('dev.off()')
self.rcmd('sink("' + self.out_mdl.replace('\\','/') + '_summary.txt")')
self.rcmd('cat("\nFull CART (cp=0)...\n\n")')
self.rcmd('print(summary(mdlall))')
self.rcmd('cat("\n\nModified CART (using",str(mdlall.cp),"as complexity parameter from Full CART)...\n\n")')
self.rcmd('print(summary(mdl))')
self.rcmd('sink()')
# grid data
self.grids2r()
# predict with model
self.msg(' predict CART in R...')
self.rcmd('pred <- predict(mdl, newdata=datpred, na.action=na.pass, type="prob")[,2]') # the probability of it being the second answer ( = 1 = presence)
self.rcmd('dim(pred) <- c(' + self.header['nrows'] + ', ' + self.header['ncols'] + ')')
# save model and data
self.rcmd('save(dat, mdl, datpred, pred, file = "' + self.out_mdl.replace('\\','/') + '.rdata")')
# prediction to grid
self.pred2gis()
self.finalize()
if __name__ == "__main__":
# main call
if not debug:
fxn = sys.argv[1] # function switch as first argument
if fxn == 'glm':
GLM()
elif fxn == 'gam':
GAM()
elif fxn == 'cart':
CART()
|
ArcRstats
|
/ArcRstats-0.8.alpha.zip/ArcRstats-0.8.alpha/arc_r/ArcRstats_0.py
|
ArcRstats_0.py
|
import os
import collections
from hashlib import sha512
from django.contrib.admin.util import NestedObjects
from django.contrib.auth.hashers import BasePasswordHasher
from django.utils.six import add_metaclass
from django.core.urlresolvers import reverse
from django.http import QueryDict
# this is just included to make sure our monkey patches are applied
from .forms import Form
import {{ project_name }}
def get_size(start_path = '.'):
"""http://stackoverflow.com/questions/1392413/calculating-a-directory-size-using-python"""
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
class IterableChoiceEnum(type):
def __iter__(self):
"""Simply return the iterator of the _choices tuple"""
return iter(self._choices)
@add_metaclass(IterableChoiceEnum)
class ChoiceEnum(object):
"""
This creates an iterable *class* (as opposed to an iterable *instance* of a
class). Subclasses must define a class variable called `_choices` which is a
list of 2-tuples. Subclasses can be passed directly to a field as the
`choice` kwarg.
For example:
class FooType(ChoiceEnum):
A = 1
B = 2
_choices = (
(A, "Alpha"),
(B, "Beta"),
)
class SomeModel(models.Model):
foo = models.ChoiceField(choices=FooType)
"""
_choices = ()
# http://stackoverflow.com/questions/5434400/python-is-it-possible-to-make-a-class-iterable-using-the-standard-syntax
# stolen from werkzeug.http
def parse_range_header(value):
"""Parses a range header into a :class:`~werkzeug.datastructures.Range`
object. If the header is missing or malformed `None` is returned.
`ranges` is a list of ``(start, stop)`` tuples where the ranges are
non-inclusive.
.. versionadded:: 0.7
"""
if not value or '=' not in value:
return None
ranges = []
last_end = 0
units, rng = value.split('=', 1)
units = units.strip().lower()
for item in rng.split(','):
item = item.strip()
if '-' not in item:
return None
if item.startswith('-'):
if last_end < 0:
return None
begin = int(item)
end = None
last_end = -1
elif '-' in item:
begin, end = item.split('-', 1)
begin = int(begin)
if begin < last_end or last_end < 0:
return None
if end:
end = int(end) + 1
if begin >= end:
return None
else:
end = None
last_end = end
ranges.append((begin, end))
return units, ranges
def will_be_deleted_with(obj):
"""
Pass in any Django model object that you intend to delete.
This will iterate over all the model classes that would be affected by the
deletion, yielding a two-tuple: the model class, and a set of all the objects of
that type that would be deleted.
This ignores any models that are not in the `vcp` package.
"""
collector = NestedObjects(using="default")
collector.collect([obj])
# the collector returns a list of all objects in the database that
# would be deleted if `obj` were deleted.
for cls, list_of_items_to_be_deleted in collector.data.items():
# ignore any classes that aren't in the vcp package
if not cls.__module__.startswith(vcp.__name__):
continue
# remove obj itself from the list
if cls == obj.__class__:
list_of_items_to_be_deleted = set(item for item in list_of_items_to_be_deleted if item.pk != obj.pk)
if len(list_of_items_to_be_deleted) == 0:
continue
yield cls, list_of_items_to_be_deleted
def build_url(*args, **kwargs):
params = kwargs.pop('params', {})
url = reverse(*args, **kwargs)
if not params: return url
qdict = QueryDict('', mutable=True)
for k, v in params.iteritems():
if type(v) is list: qdict.setlist(k, v)
else: qdict[k] = v
return url + '?' + qdict.urlencode()
class DrupalPasswordHasher(BasePasswordHasher):
'''
Hashes a Drupal 7 password with the prefix 'drupal'
Used for legacy passwords from VCP 2.0.
snippet from https://djangosnippets.org/snippets/2729/#c4520
modified for compatibility with Django 1.6
'''
algorithm = "drupal"
iter_code = 'C'
salt_length = 8
def encode(self, password, salt, iter_code=None):
"""The Drupal 7 method of encoding passwords"""
_ITOA64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
if iter_code == None:
iterations = 2 ** _ITOA64.index(self.iter_code)
else:
iterations = 2 ** _ITOA64.index(iter_code)
# convert these to bytestrings to get rid of dumb decoding errors:
salt = str(salt)
password = str(password)
hashed_string = sha512(salt + password).digest()
for i in range(iterations):
hashed_string = sha512(hashed_string + password).digest()
l = len(hashed_string)
output = ''
i = 0
while i < l:
value = ord(hashed_string[i])
i = i + 1
output += _ITOA64[value & 0x3f]
if i < l:
value |= ord(hashed_string[i]) << 8
output += _ITOA64[(value >> 6) & 0x3f]
if i >= l:
break
i += 1
if i < l:
value |= ord(hashed_string[i]) << 16
output += _ITOA64[(value >> 12) & 0x3f]
if i >= l:
break
i += 1
output += _ITOA64[(value >> 18) & 0x3f]
long_hashed = "%s$%s%s%s" % (self.algorithm, iter_code,
salt, output)
return long_hashed[:59]
def verify(self, password, encoded):
hash = encoded.split("$")[1]
iter_code = hash[0]
salt = hash[1:1 + self.salt_length]
test_encoded = self.encode(password, salt, iter_code)
return encoded == test_encoded
|
ArcUtils
|
/ArcUtils-0.1.0.tar.gz/ArcUtils-0.1.0/arc_utils/__init__.py
|
__init__.py
|
import types
from django.forms.widgets import RadioSelect
from django.forms.forms import BoundField, Form
from django import forms
from django.db import models
from django.forms.models import ModelForm
from django.forms.widgets import CheckboxInput, ClearableFileInput, DateInput, CheckboxSelectMultiple
from django.forms.util import ErrorList
from django.utils.html import format_html, format_html_join
from django.utils.encoding import force_text
class BootstrapFormWrapper(object):
def __getitem__(self, name):
"""
Add some useful attributes to the boundfield objects
"""
bound_field = super(BootstrapFormWrapper, self).__getitem__(name)
if isinstance(bound_field.field.widget, CheckboxInput):
bound_field.is_checkbox = True
if isinstance(bound_field.field.widget, DateInput):
bound_field.is_date = True
if isinstance(bound_field.field.widget, CheckboxSelectMultiple):
bound_field.is_multi_checkbox = True
classes = bound_field.field.widget.attrs.get("class", "")
if isinstance(bound_field.field.widget, (forms.widgets.TextInput, forms.widgets.Textarea)):
bound_field.field.widget.attrs['class'] = classes + " form-control"
return bound_field
class BootstrapForm(BootstrapFormWrapper, Form):
pass
class BootstrapModelForm(BootstrapFormWrapper, ModelForm):
pass
forms.Form = BootstrapForm
forms.ModelForm = BootstrapModelForm
# monkey patch the ClearableFileInput so it looks better
ClearableFileInput.initial_text = 'Currently'
ClearableFileInput.input_text = 'Change'
ClearableFileInput.clear_checkbox_label = 'Clear'
ClearableFileInput.template_with_initial = '%(initial_text)s: %(initial)s %(clear_template)s %(input_text)s: %(input)s'
ClearableFileInput.template_with_clear = '<label class="clear-label" for="%(clear_checkbox_id)s">%(clear)s %(clear_checkbox_label)s</label><br />'
# monkey patch the ErrorList so it has a bootstrap css class (text-danger)
ErrorList.as_ul = lambda self: '' if not self else format_html('<ul class="errorlist text-danger">{0}</ul>', format_html_join('', '<li>{0}</li>', ((force_text(e),) for e in self)))
# monkey patch BoundFields so that it has an error_class attribute that returns
# "has-error" or the empty string
BoundField.error_class = lambda self: "has-error" if self.errors else ""
class CustomDatePickerInput(DateTimePicker):
''' sets up default options for our datepickers '''
def __init__(self, attrs=None, format=None, options=None, div_attrs=None, icon_attrs=None):
if options == None: options = dict()
# define our custom options here:
options['pickTime'] = False
options['format'] = 'MM/DD/YYYY'
super(CustomDatePickerInput, self).__init__(attrs, format, options, div_attrs, icon_attrs)
class CustomDateTimePickerInput(DateTimePicker):
''' sets up default options for our datetimepickers '''
def __init__(self, attrs=None, format=None, options=None, div_attrs=None, icon_attrs=None):
if options == None: options = dict()
# define our custom options here:
options['sideBySide'] = True # FIXME: doesn't seem to work properly.
options['format'] = 'MM/DD/YYYY HH:mm'
super(CustomDateTimePickerInput, self).__init__(attrs, format, options, div_attrs, icon_attrs)
class RadioSelectWithBetterSubwidgets(RadioSelect):
"""
This class overrides the subwidgets method, so that it provides the
subwidget, and the choice value that the subwidget represents
"""
def subwidgets(self, name, value, attrs=None, choices=()):
# the normal subwidgets method only returns the widget, but we also want the choice value
for widget, choice in zip(self.get_renderer(name, value, attrs, choices), self.choices):
yield widget, choice[0]
class CustomForm(Form):
def __init__(self, *args, **kwargs):
super(CustomForm, self).__init__(*args, **kwargs)
def _add_error(self, field_name, error):
self._errors.setdefault(field_name, self.error_class()).append(error)
self.cleaned_data.pop(field_name, None)
def __iter__(self):
for bound_field in super(CustomForm, self).__iter__():
if isinstance(bound_field.field.widget, CheckboxInput):
bound_field.is_checkbox = True
if isinstance(bound_field.field.widget, DateInput):
bound_field.is_date = True
yield bound_field
class CustomModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(CustomModelForm, self).__init__(*args, **kwargs)
def __iter__(self):
for bound_field in super(CustomModelForm, self).__iter__():
if isinstance(bound_field.field.widget, CheckboxInput):
bound_field.is_checkbox = True
if isinstance(bound_field.field.widget, DateInput):
bound_field.is_date = True
yield bound_field
def _add_error(self, field_name, error):
self._errors.setdefault(field_name, self.error_class()).append(error)
self.cleaned_data.pop(field_name, None)
class FilterForm(CustomForm):
"""
Handles filtering of list views. Subclasses should override the items() method
"""
@property
def values(self):
"""
This returns a dict with the initial data on the form, and any possible
cleaned data values. If a field has an initial value and a
cleaned_data, the cleaned_data has precedence
"""
if not hasattr(self, "_values"):
self._values = self._merge_initial_and_cleaned_data()
return self._values
def items(self):
"""
Subclasses should override this and return an iterable of items that
match the criteria in the self.values dict
"""
return []
def _merge_initial_and_cleaned_data(self):
if self.is_bound:
# populate the cleaned_data attribute
self.is_valid()
else:
self.cleaned_data = {}
# combine the cleaned_data with the initial data
initial = dict((k, self.initial.get(k, field.initial)) for k, field in self.fields.items())
return dict(initial.items() + self.cleaned_data.items())
|
ArcUtils
|
/ArcUtils-0.1.0.tar.gz/ArcUtils-0.1.0/arc_utils/forms.py
|
forms.py
|
from __future__ import print_function
import sys
if sys.version_info < (3, 0):
print("This code requires Python 3.x and is tested with version 3.5.x ")
print("Looks like you are trying to run this using "
"Python version: %d.%d " % (sys.version_info[0],
sys.version_info[1]))
print("Exiting...")
sys.exit(1)
import random
from hut import Hut
from knight import Knight
from orcrider import OrcRider
from gameutils import print_bold
class AttackOfTheOrcs:
"""Main class to play Attack of The Orcs game"""
def __init__(self):
self.huts = []
self.player = None
def get_occupants(self):
"""Return a list of occupant types for all huts.
.. todo::
Prone to bugs if self.huts is not populated.
Chapter 2 talks about catching exceptions
"""
return [x.get_occupant_type() for x in self.huts]
def show_game_mission(self):
"""Print the game mission in the console"""
print_bold("Mission:")
print(" 1. Fight with the enemy.")
print(" 2. Bring all the huts in the village under your control")
print("---------------------------------------------------------\n")
def _process_user_choice(self):
"""Process the user input for choice of hut to enter"""
verifying_choice = True
idx = 0
print("Current occupants: %s" % self.get_occupants())
while verifying_choice:
user_choice = input("Choose a hut number to enter (1-5): ")
# --------------------------------------------------------------
# try...except illustration for chapter on exception handling.
# (Attack Of The Orcs v1.1.0)
# --------------------------------------------------------------
try:
idx = int(user_choice)
except ValueError as e:
print("Invalid input, args: %s \n" % e.args)
continue
try:
if self.huts[idx-1].is_acquired:
print("You have already acquired this hut. Try again."
"<INFO: You can NOT get healed in already acquired hut.>")
else:
verifying_choice = False
except IndexError:
print("Invalid input : ", idx)
print("Number should be in the range 1-5. Try again")
continue
return idx
def _occupy_huts(self):
"""Randomly occupy the huts with one of, friend, enemy or 'None'"""
for i in range(5):
choice_lst = ['enemy', 'friend', None]
computer_choice = random.choice(choice_lst)
if computer_choice == 'enemy':
name = 'enemy-' + str(i+1)
self.huts.append(Hut(i+1, OrcRider(name)))
elif computer_choice == 'friend':
name = 'knight-' + str(i+1)
self.huts.append(Hut(i+1, Knight(name)))
else:
self.huts.append(Hut(i+1, computer_choice))
def play(self):
"""Workhorse method to play the game.
Controls the high level logic to play the game. This is called from
the main program to begin the game execution.
"""
self.player = Knight()
self._occupy_huts()
acquired_hut_counter = 0
self.show_game_mission()
self.player.show_health(bold=True)
while acquired_hut_counter < 5:
idx = self._process_user_choice()
self.player.acquire_hut(self.huts[idx-1])
if self.player.health_meter <= 0:
print_bold("YOU LOSE :( Better luck next time")
break
if self.huts[idx-1].is_acquired:
acquired_hut_counter += 1
if acquired_hut_counter == 5:
print_bold("Congratulations! YOU WIN!!!")
if __name__ == '__main__':
game = AttackOfTheOrcs()
game.play()
|
ArcWar
|
/ArcWar-2.0.0.tar.gz/ArcWar-2.0.0/wargame/attackoftheorcs.py
|
attackoftheorcs.py
|
from __future__ import print_function
from abstractgameunit import AbstractGameUnit
from gameutils import print_bold
class Knight(AbstractGameUnit):
"""Class that represents the game character 'Knight'
The player instance in the game is a Knight instance. Other Knight
instances are considered as 'friends' of the player and is
indicated by the attribute `self.unit_type` .
"""
def __init__(self, name='Sir Foo'):
super().__init__(name=name)
self.max_hp = 40
self.health_meter = self.max_hp
self.unit_type = 'friend'
def info(self):
"""Print basic information about this character.
Overrides AbstractGameUnit.info
"""
print("I am a Knight!")
def acquire_hut(self, hut):
"""'Fight' the combat (command line) to acquire the hut
:arg Hut hut: The hut that needs to be acquired.
.. todo:: Refactor this method as an exercise
Example: Can you use self.enemy instead of calling
hut.occupant every time?
"""
print_bold("Entering hut %d..." % hut.number, end=' ')
is_enemy = (isinstance(hut.occupant, AbstractGameUnit) and
hut.occupant.unit_type == 'enemy')
continue_attack = 'y'
# Code block that tells what to do when you see, an enemy or a friend
# or no one in the hut.
# TODO: Refactor this.
if is_enemy:
print_bold("Enemy sighted!")
self.show_health(bold=True, end=' ')
hut.occupant.show_health(bold=True, end=' ')
while continue_attack:
continue_attack = input("\n...continue attack? (y/n): ")
if continue_attack == 'n':
self.run_away()
break
self.attack(hut.occupant)
if hut.occupant.health_meter <= 0:
print("")
hut.acquire(self)
break
if self.health_meter <= 0:
print("")
break
else:
if hut.get_occupant_type() == 'unoccupied':
print_bold("Hut is unoccupied")
else:
print_bold("Friend sighted!")
hut.acquire(self)
self.heal()
def run_away(self):
"""Abandon the combat and run away from the hut
If the player is losing the combat, there is an option
to leave the hut. A strategy to rejuvenate and restart the combat
for a better chance of winning.
..seealso :: :py:meth:`self.acquire_hut`
"""
print_bold("RUNNING AWAY...")
self.enemy = None
|
ArcWar
|
/ArcWar-2.0.0.tar.gz/ArcWar-2.0.0/wargame/knight.py
|
knight.py
|
from __future__ import print_function
import random
from abc import ABCMeta, abstractmethod
from gameutils import print_bold, weighted_random_selection
from gameuniterror import GameUnitError
class AbstractGameUnit(metaclass=ABCMeta):
"""Abstract class to represent a game character (or a 'unit')"""
def __init__(self, name=''):
self.max_hp = 0
self.health_meter = 0
self.name = name
self.enemy = None
self.unit_type = None
@abstractmethod
def info(self):
"""Print information about this game unit.
Abstract method. See subclasses for implementation.
"""
pass
def attack(self, enemy):
"""The main logic to 'attack' the enemy unit
Determines injured unit and the amount of injury
.. todo:: Check if enemy exists!
"""
injured_unit = weighted_random_selection(self, enemy)
injury = random.randint(10, 15)
injured_unit.health_meter = max(injured_unit.health_meter - injury, 0)
print("ATTACK! ", end='')
self.show_health(end=' ')
enemy.show_health(end=' ')
def heal(self, heal_by=2, full_healing=True):
"""Heal the unit replenishing its hit points"""
if self.health_meter == self.max_hp:
return
if full_healing:
self.health_meter = self.max_hp
else:
self.health_meter += heal_by
# ------------------------------------------------------------------
# raise a custom exception. Refer to chapter on exception handling
# ------------------------------------------------------------------
if self.health_meter > self.max_hp:
raise GameUnitError("health_meter > max_hp!", 101)
print_bold("You are HEALED!", end=' ')
self.show_health(bold=True)
def reset_health_meter(self):
"""Reset the `health_meter` (assign default hit points)"""
self.health_meter = self.max_hp
def show_health(self, bold=False, end='\n'):
"""Print info on the current health reading of this game unit"""
# TODO: what if there is no enemy?
msg = "Health: %s: %d" % (self.name, self.health_meter)
if bold:
print_bold(msg, end=end)
else:
print(msg, end=end)
|
ArcWar
|
/ArcWar-2.0.0.tar.gz/ArcWar-2.0.0/wargame/abstractgameunit.py
|
abstractgameunit.py
|
__module_name__ = "_Arrow.py"
__author__ = ", ".join(["Michael E. Vinyard"])
__email__ = ", ".join(["[email protected]",])
# import packages #
# --------------- #
import h5py
import licorice_font
# import local dependencies #
# ------------------------- #
from .._parse_arrow._read_arrow_chromosome import _read_arrow_chromosome
from .._parse_arrow._add_ArchR_metadata import _add_ArchR_metadata
from .._parse_arrow._add_matrix_parameters import _add_matrix_parameters
from .._compose_adata._compose_anndata import _compose_anndata
class _Arrow:
"""Class for reading an Arrow File from .h5"""
def __init__(
self,
path,
matrices=["GeneScoreMatrix", "TileMatrix"],
metadata_keys=["ArchRVersion", "Class"],
silent=False,
verbose=False
):
self._path = path
self._file = h5py.File(self._path)
self._silent = silent
self._verbose = verbose
_add_ArchR_metadata(self, metadata_keys=metadata_keys)
_add_matrix_parameters(self, matrices)
def to_adata(self, use_matrix="GeneScoreMatrix", outpath="./", write_h5ad=True):
self._use_matrix = use_matrix
self._outpath = outpath
if not self._silent:
mtx = licorice_font.font_format(self._use_matrix, ["BOLD", "BLUE"])
print("Reading ArchR {} to AnnData".format(mtx))
self._DataDict = _read_arrow_chromosome(self._file, self._use_matrix, self._verbose)
self._adata = _compose_anndata(DataDict=self._DataDict,
metadata=self._file['Metadata'],
feature_df=self._file[self._use_matrix]["Info"]["FeatureDF"],
use_matrix=self._use_matrix,
write_h5ad=write_h5ad,
outpath=outpath,
silent=self._silent,
)
|
ArchR-h5ad
|
/ArchR_h5ad-0.0.12-py3-none-any.whl/ArchR_h5ad/_main/_Arrow.py
|
_Arrow.py
|
__module_name__ = "_read_arrow_chromosome.py"
__author__ = ", ".join(["Michael E. Vinyard"])
__email__ = ", ".join(["[email protected]",])
# import packages #
# --------------- #
import numpy as np
import scipy.sparse
from tqdm.notebook import tqdm
# import local dependencies #
# ------------------------- #
from .._utility_functions._ordered_chromosomes import _ordered_chromosomes
def _return_sum_chromosome_axis_sums(chromosome):
colsums = np.array(chromosome["colSums"]).flatten().sum()
rowsums = np.array(chromosome["rowSums"]).flatten().sum()
return np.array([colsums, rowsums]).sum()
def _return_zero_rows(colsums):
return np.where(colsums == 0)[0]
def _get_matrix_size(chromosome):
""""""
ncols = np.array(chromosome["colSums"]).flatten().shape[0]
nrows = np.array(chromosome["rowSums"]).flatten().shape[0]
return [ncols, nrows]
def _initialize_empty_chromosome_data_matrix(chromosome):
[ncols, nrows] = _get_matrix_size(chromosome)
return np.zeros([ncols, nrows])
def _return_jLengths(chromosome):
return np.append(0, np.array(chromosome["jLengths"]).flatten()).cumsum()
def _fetch_chromosome_data_from_arrow_h5(chromosome, binary):
colsums = np.array(chromosome["colSums"]).flatten()
rowsums = np.array(chromosome["rowSums"]).flatten()
axis_sums = _return_sum_chromosome_axis_sums(chromosome)
zero_rows = _return_zero_rows(colsums)
if axis_sums.sum() == 0:
print("\tNo features / cells found in chromosome...")
return None
else:
X_empty = _initialize_empty_chromosome_data_matrix(chromosome)
j_lengths = _return_jLengths(chromosome)
i = np.array(chromosome["i"]).flatten()
if not binary:
x = np.array(chromosome["x"]).flatten()
else:
x = np.ones(len(i))
row_adj = 0
row_sums = []
for row in range(len(X_empty)):
if not row in zero_rows:
j_len_i = j_lengths[row_adj]
if not row_adj == len(j_lengths):
j_len_j = j_lengths[int(row_adj + 1)]
else:
j_len_j = j_len_i
row_vals = x[j_len_i:j_len_j]
row_sums.append(row_vals.sum())
idx = i[j_len_i:j_len_j] - 1
row_adj += 1
X_empty[row, idx] = row_vals
return scipy.sparse.csr_matrix(X_empty)
def _read_arrow_chromosome(h5_file, use_matrix="GeneScoreMatrix", verbose=False):
chromosomes = list(h5_file[use_matrix].keys())
chromosomes.remove("Info")
if use_matrix == "TileMatrix":
binary = True
else:
binary = False
DataDict = {}
if verbose:
print("Loading chromosomes from Arrow:")
for chrom_key in tqdm(_ordered_chromosomes(), desc="Chromosomes"):
if chrom_key in chromosomes:
chromosome = h5_file[use_matrix][chrom_key]
if verbose:
print("- {}".format(chrom_key))
DataDict[chrom_key] = _fetch_chromosome_data_from_arrow_h5(chromosome, binary)
else:
print(" - Warning: {} not detected!".format(chrom_key))
return DataDict
|
ArchR-h5ad
|
/ArchR_h5ad-0.0.12-py3-none-any.whl/ArchR_h5ad/_parse_arrow/_read_arrow_chromosome.py
|
_read_arrow_chromosome.py
|
# archiTop
Archidekt to TableTop export cli
---
This project aims to smoothen the export process from a constructed [Magic the Gathering](https://magic.wizards.com/en) card deck in [Archidekt](https://archidekt.com/) to the game [TableTop Simulator](https://store.steampowered.com/app/286160/Tabletop_Simulator/).
## Motivation
Currently, third third party tools do exist to aid with this process, but these are neither smooth to use
nor do they fulfill all the features that would smoothen the magic experience.
The two most noteworthy alternatives are:
1. **[Frogtown](https://www.frogtown.me/)**
- Doesn't allow to import directly from tabletop, requiring user to export and import
- Doesn't keep track of the card versions used in the deck (basic lands will update to the most recent)
- Usage is slow, two step process required to generate and download deck
- Doesn't separate commander cards from main deck
2. **[Tabletop scryfall importer](https://steamcommunity.com/sharedfiles/filedetails/?id=1838051922)**
- Unexpected behaviour when multiple people import at the same time
- Doesn't include tokens in the exported deck
- Doesn't separate commander cards from main deck
## What does this tool do?
This tool converts an Archidekt deck into Tabletop Simulator json format, able to be imported onto any tabletop board.
The cards contained, deck-name and thumbnail will be extracted for given Archidekt deck-id.
## Installation
The package is being hosted in PyPy, install using
`pip install architop`
## Usage
The tool is used via the commandline, runnable with
`architop <deckID>`
Additional usage information can be acquired via the help command
`architop -h`
## Example Usage
Let's take one of my decks as example.
Exporting the deck https://archidekt.com/decks/94674#Maximum_Borkdrive is as simple as copying the deck-id `94674`.
By running the tool with the given deck-id:
`archiDekt 94674`, archiTop will export the deck as TableTop Simulator compatible file, alongside the thumbnail used for the deck in Archidekt.
Both files created will be named accordingly to the deck name in Archidekt:

Now all that's left to do is to move the two files into the TableTop Objects folder.
The directory can vary for your Tabletop installation, based on OS.
You can find the path via the Tabletop Simulator game configurations:

## Use of altered cards
You can optionally configure the tool to load alternate art versions of cards, by executing architop with the `-a` option:
`architop <deckId> -a <path to .json file>`
The altered art json file, follows the format below:
```json
example_altered_cards.json
{
"Pyroblast": "https://architop-altered.s3.eu-west-2.amazonaws.com/Pyroblast.png",
"Red Elemental Blast": "https://architop-altered.s3.eu-west-2.amazonaws.com/Red+Elemental+Blast.png",
"Aetherflux Reservoir": "https://architop-altered.s3.eu-west-2.amazonaws.com/Aetherflux+Reservoir.png",
"Chaos Warp": "https://architop-altered.s3.eu-west-2.amazonaws.com/Chaos+Warp.png",
"Dockside Extortionist": "https://architop-altered.s3.eu-west-2.amazonaws.com/Dockside+Extortionist.png",
"Sol Ring": "https://architop-altered.s3.eu-west-2.amazonaws.com/Sol+Ring.png"
}
```
Have fun playing 🎉
## Roadmap
The current plans for the repository are being tracked via [github issues](https://github.com/Julian-Brendel/archiTop/issues).
|
ArchiTop
|
/ArchiTop-0.3.1.tar.gz/ArchiTop-0.3.1/README.md
|
README.md
|
import argparse
import json
from archiTop.config import get_spin_logger
from archiTop.deck_builder import DeckBuilderWrapper
from archiTop.deck_fetcher import ArchidektFetcher, MoxfieldFetcher
from archiTop.scryfall import ScryfallDeckBuilder, syncronize_scryfall_data
spin_logger = get_spin_logger(__name__)
def setup_argparse():
parser = argparse.ArgumentParser(description='Convert archidekt deck to TableTop')
parser.add_argument('deckID',
help='Archidekt deck-ID to convert')
parser.add_argument('-n', '--name', type=str,
help='Optional deckname to overwrite the archidekt deckname')
parser.add_argument('-c', '--custom_back_url', type=str,
help='Use custom card-back image url')
parser.add_argument('-p', '--path', type=str,
help='Path to write output to')
parser.add_argument('-a', '--altered', type=str,
help='File containing image-urls by card name to use instead of scryfall')
return parser.parse_args()
def main():
args = setup_argparse()
# ensure scryfall data is up to date
syncronize_scryfall_data()
# decide which service to request deck from
if args.deckID.isnumeric():
spin_logger.debug('Fetching Archidekt deck', extra={'user_waiting': False})
deck = ArchidektFetcher(args.deckID).get_deck()
else:
spin_logger.debug('Fetching Moxfield deck', extra={'user_waiting': False})
deck = MoxfieldFetcher(args.deckID).get_deck()
# overwrite deckname if optional argument is specified
deck.name = args.name if args.name else deck.name
altered_cards_index = json.load(open(args.altered, "r")) if args.altered else {}
# enrich deck information with scryfall data (cmc, type_lines etc.)
scryfall_deck = ScryfallDeckBuilder(deck, altered_cards_index).construct_deck()
builder = DeckBuilderWrapper(scryfall_deck, custom_back_url=args.custom_back_url)
builder.construct_final_deck()
builder.save_deck(args.path)
if __name__ == '__main__':
main()
|
ArchiTop
|
/ArchiTop-0.3.1.tar.gz/ArchiTop-0.3.1/archiTop/__main__.py
|
__main__.py
|
from dataclasses import dataclass
from functools import reduce
from typing import List
from archiTop.scryfall.scryfall_loader import load_scryfall_id_index
class ScryfallCard:
"""Class containing information for scryfall card object."""
related_cards = set()
def __init__(self,
scryfall_card_data: dict,
resolve_tokens=True,
quantity=1,
commander=False,
card_side=0,
altered_url: str = None):
self.id_index = load_scryfall_id_index()
self.commander = commander
self.quantity = quantity
self.name = scryfall_card_data['name']
self.type_line = scryfall_card_data['type_line']
self.cmc = scryfall_card_data['cmc']
cmc_string = f'CMC{int(self.cmc)}'
self.tabletop_name = f'{self.name} - {cmc_string}\n' \
f'{self.type_line}'
self.id = scryfall_card_data['id']
if altered_url:
self.image_url = altered_url
else:
if 'image_uris' in scryfall_card_data:
# extract image_url, choosing high rez if available
image_uris = scryfall_card_data['image_uris']
elif 'card_faces' in scryfall_card_data: # card is a double sized card
image_uris = scryfall_card_data['card_faces'][card_side]['image_uris']
if card_side == 0:
self.related_cards = {ScryfallCard(self.id_index[scryfall_card_data['id']],
resolve_tokens=False,
card_side=1)}
else:
raise Exception('Unknown card-type encountered')
if 'large' in image_uris:
self.image_url = image_uris['large']
else:
self.image_url = image_uris['normal']
if resolve_tokens:
related_objects = scryfall_card_data.get('all_parts', ())
related_tokens = list(
filter(lambda related_object: related_object['component'] == 'token',
related_objects))
related_meld_cards = list(
filter(lambda related_object: related_object['component'] == 'meld_result',
related_objects))
related_ids = set([related_object['id'] for related_object in
related_tokens + related_meld_cards])
self.related_cards |= {ScryfallCard(self.id_index[related_id],
resolve_tokens=False)
for related_id in related_ids}
def __repr__(self):
commander_identifier = '[Commander]' if self.commander else ''
return f'Card{commander_identifier}({self.quantity: <2} x {self.name})'
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, ScryfallCard):
return self.id == other.id
return False
def __hash__(self):
return hash(self.id)
@dataclass
class ScryfallDeck:
"""Class containing information for mtg deck of cards.
This consists of the mainboard, sideboard and token / emblems."""
mainboard: List[ScryfallCard] # list containing cards in mainboard
related_cards: List[ScryfallCard] # list containing related cards (tokens, ...)
name: str # name of deck
thumbnail: bytes # image bytes for deck thumbnail
def __repr__(self):
total_count = reduce(lambda a, b: a + b.quantity, self.mainboard, 0)
return (f'Deck[{self.name}](\n'
f'- {total_count: <3} total cards\n'
f'- {len(self.mainboard): <3} unique cards\n'
f'- {len(self.related_cards): <3} related cards)')
|
ArchiTop
|
/ArchiTop-0.3.1.tar.gz/ArchiTop-0.3.1/archiTop/scryfall/data_types.py
|
data_types.py
|
from collections import OrderedDict
from copy import deepcopy
from archiTop.base_classes import DeckBuilder
from archiTop.resources import (card_asset_template, card_deck_template,
card_template)
from archiTop.scryfall.data_types import ScryfallCard
class MultiCardDeckBuilder(DeckBuilder):
""""MultiCardDeckBuilder class implementing abstract DeckBuilder class.
Used for card decks with multiple cards."""
def __init__(self, *args):
self.card_deck_json = deepcopy(card_deck_template)
self.contained_objects = []
self.deck_ids = []
self.custom_deck = OrderedDict()
super().__init__(*args)
def __repr__(self):
unique_cards = len(set(self.deck_ids))
return f'CardDeck({len(self.deck_ids)} total cards, {unique_cards} unique cards)'
def _populate_card_template(self, card: ScryfallCard):
"""Creates a new TableTop card object and fills information from card class.
Each card in deck needs one card object, therefore cards with quantity > 1 will be
duplicated.
Same cards, even when duplicated will keep the same ID.
Once populated, card object is inserted into contained_objects and id added to deck_ids.
Args:
card: Card to create card object for
"""
card_json = deepcopy(card_template)
card_json['CardID'] = self.current_card_id
card_json['Nickname'] = card.tabletop_name
# create one object per quantity
for _ in range(card.quantity):
self.contained_objects.append(card_json)
self.deck_ids.append(self.current_card_id)
self.current_card_id += 100
def _populate_card_asset_template(self, card: ScryfallCard):
"""Creates a new TableTop card asset object and fills with information from card class.
There should only exist on card asset template for each unique card.
Therefor cards with quantity > 1 do only get one card asset.
Asset matching is done with insertion order of asset objects.
Order in the ContainedObjects, DeckID's must match the order of card assets.
Once populated, card asset is inserted in custom deck and asset id is incremented.
Args:
card: Card to create asset for
"""
card_asset_json = deepcopy(card_asset_template)
card_asset_json['FaceURL'] = card.image_url
card_asset_json['BackURL'] = self.card_back_url
self.custom_deck[str(self.current_card_asset_id)] = card_asset_json
self.current_card_asset_id += 1
def create_deck(self) -> dict:
"""Create the json structure for the card deck containing multiple cards.
Returns:
TableTop card deck json containing multiple cards
"""
for card in self.cards:
self._populate_card_template(card)
self._populate_card_asset_template(card)
self.card_deck_json['ContainedObjects'] = self.contained_objects
self.card_deck_json['DeckIDs'] = self.deck_ids
self.card_deck_json['CustomDeck'] = self.custom_deck
self.card_deck_json['Transform']['rotZ'] = 180 if self.hidden else 0
return self.card_deck_json
|
ArchiTop
|
/ArchiTop-0.3.1.tar.gz/ArchiTop-0.3.1/archiTop/deck_builder/multi_card_deck_builder.py
|
multi_card_deck_builder.py
|
import json
import sys
from copy import deepcopy
from pathlib import Path
from typing import List, Optional
from archiTop.config import get_spin_logger, load_config
from archiTop.deck_builder.multi_card_deck_builder import MultiCardDeckBuilder
from archiTop.deck_builder.single_card_deck_builder import SingleCardDeckBuilder
from archiTop.resources import final_deck_template
from archiTop.scryfall.data_types import ScryfallCard, ScryfallDeck
spin_logger = get_spin_logger(__name__)
class DeckBuilderWrapper:
"""Wrapper class, converting Deck object into TableTop deck asset"""
custom_back_url = None
def __init__(self,
deck: ScryfallDeck,
custom_back_url: str = None):
"""Initializes deck builder wrapper with deck of cards.
Args:
deck: Deck including cards contained and additional deck information
custom_back_url: Url for image to replace the default mtg card-back
"""
self.final_deck_json = deepcopy(final_deck_template)
self.card_decks = []
self.deck = deck
if custom_back_url:
spin_logger.debug('Using custom card-back <%s>', custom_back_url,
extra={'user_waiting': False})
self.custom_back_url = custom_back_url
def construct_final_deck(self):
"""Constructs the final asset json for TableTop.
Separates mainboard cards from commander, then creates multiple card decks
for mainboard- and commander-cards.
"""
mainboard_cards = list(filter(lambda card: not card.commander, self.deck.mainboard))
commander_cards = list(filter(lambda card: card.commander, self.deck.mainboard))
# construct related cards card-deck, including tokens
if token_deck := self._construct_card_deck(self.deck.related_cards, hidden=False):
self.card_decks.append(token_deck)
# construct mainboard card-deck
if mainboard_deck := self._construct_card_deck(mainboard_cards):
self.card_decks.append(mainboard_deck)
# construct separate card-deck for commander
if commander_deck := self._construct_card_deck(commander_cards, hidden=False):
self.card_decks.append(commander_deck)
# todo: implement sideboard
# construct sideboard
if sideboard_deck := None:
self.card_decks.append(sideboard_deck)
# shift deck positions so piles do not combine
current_x_pos = 0
for deck in self.card_decks:
deck['Transform']['posX'] = current_x_pos
current_x_pos += 2.2
self.final_deck_json['ObjectStates'] = self.card_decks
def save_deck(self, export_location: str = None):
"""Saves deck and thumbnail.
Filename is determined by the chosen deck name.
If system is mac os, output will be saved to the tabletop location,
otherwise it will be stored to current directory.
Args:
export_location: Optional argument to overwrite output location
"""
deck_name = f'{self.deck.name}.json'
thumbnail_name = f'{self.deck.name}.png'
log_message = f'deck <{self.deck.name}>'
if export_location:
log_message += f' to passed location <{export_location}>'
else:
if sys.platform == 'darwin': # client is using mac os
log_message += ' to tabletop location'
table_top_save_location = load_config()['EXPORT']['MAC']
export_location = Path(Path.home(), table_top_save_location)
else:
log_message += ' to current directory'
export_location = ''
spin_logger.debug('Saving %s', log_message, extra={'user_waiting': True})
# save deck json
json.dump(self.final_deck_json, open(Path(export_location, deck_name), 'w'))
# save deck thumbnail
if self.deck.thumbnail:
with open(Path(export_location, thumbnail_name), 'wb') as file:
file.write(self.deck.thumbnail)
spin_logger.debug('Saved %s', log_message, extra={'user_waiting': False})
def _construct_card_deck(self, card_list: List[ScryfallCard],
hidden=True) -> Optional[dict]:
"""Chooses DeckBuilder based on amount of amount of cards passed.
Chooses SingleCardDeckBuilder when card list contains a single card.
MultiCardDeckBuilder when card list contains multiple cards.
Args:
card_list: List of cards to create deck asset for
hidden: Whether deck is hidden or not (face down)
Defaults to true.
Returns:
Result from deck builder or None when List is empty
"""
if len(card_list) > 1:
builder = MultiCardDeckBuilder(card_list, hidden, self.custom_back_url)
elif len(card_list) == 1:
builder = SingleCardDeckBuilder(card_list, hidden, self.custom_back_url)
else:
return None
return builder.create_deck()
|
ArchiTop
|
/ArchiTop-0.3.1.tar.gz/ArchiTop-0.3.1/archiTop/deck_builder/final_deck_builder.py
|
final_deck_builder.py
|
from typing import List, Set
import requests
from archiTop.base_classes import DeckFetcher, DeckFetcherError
from archiTop.data_types import RawCard
class ArchidektFetcher(DeckFetcher):
"""ArchidektFetcher class, implementing abstract baseclass DeckFetcher"""
base_url = 'https://archidekt.com/api/decks/%s/small/'
@staticmethod
def _parse_single_card(card: dict) -> RawCard:
"""Parses single card information from deck service into Card object.
Args:
card: Card json object to parse information from
Returns:
Card class containing parsed information from card json object
"""
card_data = card['card']
name = card_data['oracleCard']['name']
uid = card_data['uid']
quantity = card['quantity']
commander = card['category'] == 'Commander' or 'Commander' in card.get('categories', ())
return RawCard(name, quantity, uid, commander)
@staticmethod
def _handle_response(response: requests.Response):
"""Handles response from archidekt api, validating request was successful.
Raises:
DeckFetcherError: When invalid status code was encountered in response from api
Args:
response: Response object from archidekt api call
"""
try:
response.raise_for_status()
except requests.HTTPError as e:
try:
error_message = response.json()['error']
except Exception:
error_message = e
raise DeckFetcherError(f'Failed to fetch archidekt deck with error:\n{error_message}')
@staticmethod
def _parse_deck_name(raw_deck_data: dict) -> str:
"""Parses deck name from deck data fetched by `_get_raw_deck_data()`.
Args:
raw_deck_data: Raw server data fetched by deck data request
Returns:
Name of deck
"""
return raw_deck_data['name']
@staticmethod
def _get_thumbnail(raw_deck_data: dict) -> bytes:
"""Parses thumbnail url from deck data fetched by `_get_raw_deck_data()`.
Args:
raw_deck_data: Raw server data fetched by deck data request
Returns:
Thumbnail url for fetched deck information
"""
url = raw_deck_data['featured']
return requests.get(url).content
def _parse_mainboard_cards(self, data: dict) -> List[RawCard]:
# identify categories for all valid mainboard cards
valid_categories = {category['name'] for category in data['categories']
if category['includedInDeck']} - {'Sideboard'}
mainboard_cards = [card for card in data['cards']
if self._validate_mainboard_cards(card, valid_categories)]
return [self._parse_single_card(card) for card in mainboard_cards]
@staticmethod
def _validate_mainboard_cards(card: dict, mainboard_categories: Set[str]) -> bool:
"""Validates whether a single card belongs to mainboard.
Args:
card: Card json object contained in fetched deck information
mainboard_identifier: List holding valid mainboard categories
Returns:
True when card is contained in mainboard, False otherwise
"""
# return category_check and categories_checks
category = card['categories'][0] if len(card['categories']) > 0 else None
return category in mainboard_categories
|
ArchiTop
|
/ArchiTop-0.3.1.tar.gz/ArchiTop-0.3.1/archiTop/deck_fetcher/archidekt.py
|
archidekt.py
|
from typing import List, Set
import requests
from archiTop.base_classes import DeckFetcher, DeckFetcherError
from archiTop.data_types import RawCard
from archiTop.scryfall import load_scryfall_id_index
class MoxfieldFetcher(DeckFetcher):
"""MoxfieldFetcher class, implementing abstract baseclass DeckFetcher"""
base_url = ' https://api.moxfield.com/v2/decks/all/%s'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.scryfall_id_index = load_scryfall_id_index()
@staticmethod
def _parse_card(data: dict, commander: bool = False) -> RawCard:
"""Parses single card information from deck service into Card object.
Args:
card: Card json object to parse information from
Returns:
Card class containing parsed information from card json object
"""
quantity = data['quantity']
name = data['card']['name']
uid = data['card']['scryfall_id']
return RawCard(name, quantity, uid, commander)
@staticmethod
def _handle_response(response: requests.Response):
"""Handles response from moxfield api, validating request was successful.
Raises:
DeckFetcherError: When invalid status code was encountered in response from api
Args:
response: Response object from archidekt api call
"""
try:
response.raise_for_status()
except requests.HTTPError as e:
raise DeckFetcherError(f'Failed to fetch moxfield deck with error:\n{e}')
def _parse_mainboard_cards(self, data: dict) -> List[RawCard]:
"""Parses card information from deck data fetched by `_get_raw_deck_data()`.
Args:
raw_deck_data: Raw server data fetched by deck data request
Returns:
List of card json objects contained in deck
"""
mainboard_cards = [self._parse_card(card) for card in data['mainboard'].values()]
mainboard_cards += [self._parse_card(card, commander=True)
for card in data['commanders'].values()]
return mainboard_cards
@staticmethod
def _parse_deck_name(data: dict) -> str:
"""Parses deck name from deck data fetched by `_get_raw_deck_data()`.
Args:
data: Raw server data fetched by deck data request
Returns:
Name of deck
"""
return data['name']
def _get_thumbnail(self, data: dict) -> bytes:
"""Parses thumbnail url from deck data fetched by `_get_raw_deck_data()`.
Args:
data: Raw server data fetched by deck data request
Returns:
Thumbnail url for fetched deck information
"""
if data['commanders'].values():
card = list(data['commanders'].values())[0]
scryfall_card = self.scryfall_id_index[card['card']['scryfall_id']]
image_uris = scryfall_card.get('image_uris') or scryfall_card.get('card_faces')[0][
'image_uris']
return requests.get(image_uris['art_crop']).content
|
ArchiTop
|
/ArchiTop-0.3.1.tar.gz/ArchiTop-0.3.1/archiTop/deck_fetcher/moxfield.py
|
moxfield.py
|
from abc import ABC, abstractmethod
from functools import reduce
from typing import Any, List
import requests
from archiTop.config import get_spin_logger
from archiTop.data_types import RawCard, RawDeck
spin_logger = get_spin_logger(__name__)
class DeckFetcherError(Exception):
"""Exception to raise when an error was encountered during deck fetching"""
pass
class DeckFetcher(ABC):
"""Abstract baseclass to for deck fetcher"""
base_url = None
mainboard_cards: List[RawCard] = []
def __init__(self, deck_id: int):
"""Initializes deck fetcher with id of deck.
Args:
deck_id: DeckID to fetch deck information for
"""
self.deck_id = deck_id
def __repr__(self) -> str:
total_count = reduce(lambda a, b: a + b.quantity, self.mainboard_cards, 0)
return f'DeckFetcher({total_count} total cards, {len(self.mainboard_cards)} unique cards)'
def _request_raw_deck(self) -> requests.Response:
"""Fetch the deck information by querying base_url combined with the deckID.
Returns:
Deck information in json format
"""
spin_logger.debug('Downloading deck <%s>', self.deck_id, extra={'user_waiting': True})
response = requests.get(self.base_url % self.deck_id)
spin_logger.debug('Downloaded deck <%s>', self.deck_id, extra={'user_waiting': False})
return response
@staticmethod
def _parse_data(request: requests.Response) -> dict:
return request.json()
def get_deck(self) -> RawDeck:
"""Fetches and parses deck information.
Returns:
Deck of cards, containing deck information fetched
"""
raw_deck_response = self._request_raw_deck()
self._handle_response(raw_deck_response)
data = self._parse_data(raw_deck_response)
deck_name = self._parse_deck_name(data)
thumbnail = self._get_thumbnail(data)
self.mainboard_cards = self._parse_mainboard_cards(data)
return RawDeck(self.mainboard_cards, deck_name, thumbnail)
@abstractmethod
def _parse_mainboard_cards(self, data: dict) -> List[RawCard]:
raise NotImplemented
@staticmethod
@abstractmethod
def _handle_response(response: requests.Response):
"""Abstractmethod to be implemented by child class.
Validates whether request to server was successful.
Args:
response: Response from server request
"""
raise NotImplemented
@staticmethod
@abstractmethod
def _parse_deck_name(raw_deck_data: dict) -> str:
"""Abstractmethod to be implemented by child class.
Parses deck name from deck data fetched by `_get_raw_deck_data()`.
Args:
raw_deck_data: Raw server data fetched by deck data request
Returns:
Name of deck
"""
raise NotImplemented
@staticmethod
@abstractmethod
def _get_thumbnail(raw_deck_data: dict) -> bytes:
"""Abstractmethod to be implemented by child class.
Parses thumbnail url from deck data fetched by `_get_raw_deck_data()`.
Args:
raw_deck_data: Raw server data fetched by deck data request
Returns:
Thumbnail url for fetched deck information
"""
raise NotImplemented
|
ArchiTop
|
/ArchiTop-0.3.1.tar.gz/ArchiTop-0.3.1/archiTop/base_classes/deck_fetcher.py
|
deck_fetcher.py
|
Archippe is a data persistence micro service for pelops. It uses
influxdb to store incoming values and publishes the history a series
upon request.
For example, ``archippe`` should store all values from topic
``\room\temperature``. For this purpose a series with the same name is
used in influxdb. To retrieve data a message must be sent to
``\dataservice\request\room\temperature``. The message can either be a
single float or a simple json structure. In the first case, the float
value defines the time span in seconds (from=now()-floatvalue,
to=now()). The json structure consists of two timestamps and group-by in
seconds (optional):
``{"from": "2009-11-10T22:00:00Z", "to": "2009-11-10T23:00:00Z", "group-by": 60}``
(timestamp are inclusive: ``where t<=to and t>=from``; time format is
``%Y-%m-%dT%H:%M:%S.%fZ``, ``group-by`` must be integer). The result
from the query will be published to
``\dataservice\response\room\temperature``. It contains a list of a
values and their timestamp that are available for the given period:
``[{"time": 10, "value": 0.1}, {"time": 11, "value": 0.2}, ...]``.
Request json-message:
::
{
"from": "2009-11-10T22:00:00Z",
"to": "2009-11-10T23:00:00Z",
"group-by": 60 # optional (equal to 0)
}
Response json-message:
::
{
"first": "2009-11-10T22:00:01Z",
"last": "2009-11-10T22:59:23Z",
"len": 49, # entries in data list
"topic": "/test/example",
"version": 2, # version of the response format
"group-by": 0,
"data": [
{"time": "2009-11-10T22:00:01Z", "value": 17.98},
{"time": "2009-11-10T22:01:50Z", "value": 13.98},
{"time": "2009-11-10T22:03:00Z", "value": 11.98},
...
{"time": "2009-11-10T22:59:23Z", "value": 20.0}
]
}
In `pelops <https://gitlab.com/pelops/pelops>`__ exists a
``HistoryAgent``-class that implements a client side interaction with
this dataservice. A usage example can be found in
`nikippe <https://gitlab.com/pelops/nikippe>`__ - the charts
``CircularChart`` and ``SequentialChart`` rely on ``HistoryAgent`` to
keep track of old data.
.. figure:: img/Microservice%20Overview.png
:alt: Pelops Overview
Pelops Overview
``Archippe`` is part of the collection of mqtt based microservices
`pelops <https://gitlab.com/pelops>`__. An overview on the microservice
architecture and examples can be found at
(http://gitlab.com/pelops/pelops).
For Users
=========
Installation Core-Functionality
-------------------------------
Prerequisites for the core functionality are:
::
sudo apt install python3 python3-pip
Install via pip:
::
sudo pip3 install archippe
To update to the latest version add ``--upgrade`` as prefix to the
``pip3`` line above.
Install via gitlab (might need additional packages):
::
git clone [email protected]:pelops/archippe.git
cd archippe
sudo python3 setup.py install
This will install the following shell scripts: \* ``archippe``
The script cli arguments are: \* '-c'/'--config' - config file
(mandatory) \* '--version' - show the version number and exit
influxdb
--------
Installation
~~~~~~~~~~~~
Install influx database and client. For example in ubuntu to install
them use:
::
sudo apt install influxdb influxdb-client
and start the influx client with ``ìnflux``.
Configuration
~~~~~~~~~~~~~
We need to create a database (``archippe``), an admin user, and a
non-admin user with write access to this database.
Within the influx client:
::
create database archippe
use archippe
create user admin with password 'supersecret' with all privileges
create user pelops with password 'secret'
grant all on archippe to pelops
exit
YAML-Config
-----------
A yaml [1]_ file must contain four root blocks:
- mqtt - mqtt-address, mqtt-port, and path to credentials file
credentials-file (a file consisting of the entry ``mqtt`` with two
sub-entries ``mqtt-user``, ``mqtt-password``) [2]_
- logger - which log level and which file to be used
- influx - influx-address, influx-port, and path to credentials file
credentials-file (a file consisting of the entry ``influx`` with two
sub-entries ``influx-user``, ``influx-password``) [3]_
- data-persistence
- topics - list of topics that should be persisted and their types
- prefix - prefix for each topic to request historic data
- response - prefix for each topic to publish historic data
::
mqtt:
mqtt-address: localhost
mqtt-port: 1883
credentials-file: ~/credentials.yaml
log-level: INFO
logger:
log-level: DEBUG
log-file: archippe.log
data-persistence:
influx:
influx-address: homebase.w.strix.at
influx-port: 8086
credentials-file: ~/credentials.yaml
database: archippe # influx database
log-level: INFO
topics: # list of topics that should be persisted
- topic: /test/temperature
type: float # float, integer, string, boolean
- topic: /test/humidity
type: float # float, integer, string, boolean
topic-request-prefix: /dataservice/request # prefix for each topic to request historic data
topic-response-prefix: /dataservice/response # prefix for each topic to publish historic data
systemd
-------
- add systemd example.
For Developers
==============
Getting Started
---------------
This service consists of two classes ``DataPersistence`` and ``Topic``.
For each topic that should be peristet an instance of ``Topic`` is
created in ``DataPersistence``.
Changes in the yaml structure must be mirrored in
``archippe/schema.py``. It is a json-schema that verifies the provided
yaml.
MyInfluxDBClient
----------------
Wrapper for influxdb.InfluxDBClient. Takes care initializing and writing
of single datapoints to the db.
Next to the raw connectivity, this client provides two methods: \*
``write_point``: Write a single measurement value to the database
(wrapper for influxdb.write\_points method). \* ``write_points``: Write
a list of entries (timestamp, value) into the measurement of the
database.
Todos
-----
- none currently planed
Misc
----
The code is written for ``python3`` (and tested with python 3.5 on an
Raspberry Pi Zero with Raspbian Stretch).
`Merge requests <https://gitlab.com/pelops/archippe/merge_requests>`__ /
`bug reports <https://gitlab.com/pelops/archippe/issues>`__ are always
welcome.
.. [1]
Currently, pyyaml is yaml 1.1 compliant. In pyyaml On/Off and Yes/No
are automatically converted to True/False. This is an unwanted
behavior and deprecated in yaml 1.2. In copreus this autoconversion
is removed. Thus, On/Off and Yes/No are read from the yaml file as
strings (see module baseclasses.myconfigtools).
.. [2]
Mqtt and influx credentials can be stored in one file.
.. [3]
Mqtt and influx credentials can be stored in one file.
|
Archippe
|
/Archippe-0.2.1.tar.gz/Archippe-0.2.1/README.rst
|
README.rst
|
from pelops.logging.mylogger import get_child
from archippe.myinfluxdbclient import MyInfluxDBClient
import datetime
import json
class Topic:
"""
Topic handles storage and retrieval for the given mqtt-topic. It registers to topic_request and expect two different
types of messages:
* timespan in seconds to be substracted from now(). float value.
* timestamps "from" and "to" and "group-by" in secons in a json structure. e.g. ```{"from":
"2009-11-10T22:00:00Z", "to": "2009-11-10T23:00:00Z", "group-by": 60}``` (timestamp are
inclusive: "where t<=to and t>=from"; group-by must be integer)
The resulting list of timestamp/value pairs is published to topic_publish.
{
"first": "2009-11-10T22:00:01Z",
"last": "2009-11-10T22:59:23Z",
"len": 49,
"group-by": 300,
"topic": "/test/example",
"version": 2,
"data": [
{"timestamp": "2009-11-10T22:00:01Z", "value": 17.98},
{"timestamp": "2009-11-10T22:01:50Z", "value": 13.98},
{"timestamp": "2009-11-10T22:03:00Z", "value": 11.98},
...
{"timestamp": "2009-11-10T22:59:23Z", "value": 20.0}
]
}
"""
_pubsub_client = None # pubsubclient instance
_topic_sub = None # topic of interest
_topic_response = None # publish historic data
_topic_request = None # listen to data requests
_influxdb = None # influxdb client instance
_time_format = "%Y-%m-%dT%H:%M:%S.%fZ" # time format string for influxdb queries
_conversion = None # conversion method - used to convert the incoming message
def __init__(self, topic_sub, topic_request, topic_response, conversion, pubsub_client, logger, influxdb):
"""
Constructor
:param topic_sub: mqtt-topic - topic of interest
:param topic_request: mqtt-topic - listen to data requests
:param topic_response: mqtt-topic - publish results
:param pubsub_client: pubsubclient instance
:param logger: logger instance
:param influxdb: influxdb client instance
"""
self._influxdb = influxdb
self._pubsub_client = pubsub_client
self._topic_sub = topic_sub
self._topic_request = topic_request
self._topic_response = topic_response
self._conversion = conversion
self._logger = get_child(logger, __name__ + "." + self._topic_sub)
self._logger.info("Topic.__init__ - initializing")
self._logger.debug("Topic.__init__ - sub: {}, request: {}, reponse: {}, measurement: {}, conversion: {}.".
format(self._topic_sub, self._topic_request, self._topic_response,
MyInfluxDBClient.escape_name(self._topic_sub), self._conversion))
def _handler_sub(self, value):
"""
Receive values publish to the topic of interest and store store them in influxdb.
:param value: raw value
"""
value = value.decode("UTF-8")
if value is not None and len(value) > 0:
try:
value = self._conversion(value)
except ValueError as e:
self._logger.error("Topic._handler_sub - error converting value '{}' from topic '{}' "
"with conversion '{}': {}".format(value, self._topic_sub, self._conversion, e))
return
self._logger.info("received value {} on topic {}.".format(value, self._topic_sub))
self._influxdb.write_point(self._topic_sub, value)
else:
self._logger.info("received empty value on topic {}.")
def _handler_request(self, message):
"""
Processes historic data requests and publishes the result to topic_response.
:param message: Request received via topic_request. Either float value or json structur (to, from, group-by).
"""
timestamp_from, timestamp_to, group_by = self._extract_parameters(message)
if timestamp_to is None or timestamp_from is None:
self._logger.error("_handler_request - received malformed message '{}' on topic '{}'.".
format(message, self._topic_request))
else:
response = self._render_response(timestamp_from, timestamp_to, group_by)
self._logger.info("_handler_request - publishing list with {} values.".format(response["len"]))
self._pubsub_client.publish(self._topic_response, json.dumps(response))
def _render_response(self, timestamp_from, timestamp_to, group_by):
response = {
"version": 2,
"topic": self._topic_sub,
"group-by": group_by
}
response["data"] = list((self._fetch_history(timestamp_from, timestamp_to, group_by)).get_points())
response["len"] = len(response["data"])
if response["len"] > 0:
response["first"] = response["data"][0]["time"]
response["last"] = response["data"][0]["time"]
else:
response["first"] = ""
response["last"] = ""
return response
def _fetch_history(self, timestamp_from, timestamp_to, group_by):
"""
Fetch data from influxdb in the timerange: from<=t and to<=t. Optionally apply group_by.
:param timestamp_from: datetime timestamp
:param timestamp_to: datetime timestamp
:param group_by: group_by float value or None
:return: list with measurements
"""
self._logger.info("_fetch_history: topic '{}', from '{}', to '{}', group-by '{}'.".
format(self._topic_sub, timestamp_from, timestamp_to, group_by))
timestamp_to = timestamp_to.strftime(self._time_format)
timestamp_from = timestamp_from.strftime(self._time_format)
measurement = MyInfluxDBClient.escape_name(self._topic_sub)
if group_by is None:
query = 'select value as value from "{}" where time <= \'{}\' and time >= \'{}\''.\
format(measurement, timestamp_to, timestamp_from)
else:
query = 'select mean(value) as value from "{}" where time <= \'{}\' and time >= \'{}\' group by time({}s)'. \
format(measurement, timestamp_to, timestamp_from, group_by)
self._logger.debug("_fetch_history - query: '{}'.".format(query))
history = self._influxdb.client.query(query)
self._logger.debug("_fetch_history - query result: '{}'.".format(history))
return history
def _extract_parameters(self, message):
"""
Extract the parameters to, from, and group-by from the message.
:param message: Message can either be float of a json structure (to, from, group-by)
:return: timestamp_from, timestamp_to, group_by - timestamps are datetime objects and group_by is float
"""
timestamp_to = None
timestamp_from = None
group_by = None
try:
timestamp_from = datetime.datetime.utcnow() - datetime.timedelta(seconds=float(message))
timestamp_to = datetime.datetime.utcnow()
except ValueError:
message = message.decode("utf-8")
message = json.loads(message)
try:
timestamp_from = datetime.datetime.strptime(message["from"], self._time_format)
except KeyError:
self._logger.error("_extract_parameters - key 'from' not found.")
try:
timestamp_to = datetime.datetime.strptime(message["to"], self._time_format)
except KeyError:
self._logger.error("_extract_parameters - key 'to' not found.")
try:
group_by = int(message["group-by"])
except KeyError:
self._logger.info("_extract_parameters - optional key 'group-by' not found.")
except ValueError:
self._logger.error("_extract_parameters - type of entry 'group-by' is not int - parameter ignored")
return timestamp_from, timestamp_to, group_by
def start(self):
"""Subscribe topics."""
self._pubsub_client.subscribe(self._topic_sub, self._handler_sub)
self._pubsub_client.subscribe(self._topic_request, self._handler_request)
self._logger.info("started")
def stop(self):
"""Unsubscribe topics."""
self._pubsub_client.unsubscribe(self._topic_sub, self._handler_sub)
self._pubsub_client.unsubscribe(self._topic_request, self._handler_request)
self._logger.info("stopped")
|
Archippe
|
/Archippe-0.2.1.tar.gz/Archippe-0.2.1/archippe/topic.py
|
topic.py
|
from influxdb import InfluxDBClient
from pelops.logging.mylogger import get_child
import datetime
class MyInfluxDBClient:
"""
Wrapper for influxdb.MyInfluxDBClient. Takes care initializing and writing of single datapoints to the db.
In the configuration file you can choose to either provide an credentials file ("credentials-file") or to add
the credentials directly ("influx-user", "influx-password").
influx:
influx-address: localhost
influx-port: 8086
credentials-file: ~/credentials.yaml
database: archippe_test
log-level: DEBUG # log level to be used by logger
credentials-file file:
influx:
influx-password: secret
influx-username: user
"""
client = None # instance of InflucDBClient.influxdb
_influxdb_username = None
_influxdb_password = None
_influxdb_address = None
_influxdb_port = None
_influxdb_database = None
_config = None # config yaml
_logger = None # logger instance
def __init__(self, config, logger):
"""
Constructor
:param config: yaml structure
:param logger: logger instance - a child with name __name__ will be spawned.
"""
self._config = config
self._logger = get_child(logger, __name__, config)
self._logger.info("MyInfluxDBClient.__init__ - creating instance.")
self._logger.debug("MyInfluxDBClient.__init__ - config: {}".format(self._config))
self._influxdb_address = str(self._config["influx-address"])
self._influxdb_port = int(self._config["influx-port"])
self._influxdb_database = str(self._config["database"])
self._influxdb_password = str(self._config["influx-password"])
self._influxdb_username = str(self._config["influx-user"])
self.client = InfluxDBClient(host=self._influxdb_address, port=self._influxdb_port,
username=self._influxdb_username, password=self._influxdb_password,
database=self._influxdb_database)
def _get_json_entry(self, measurement, value, timestamp):
"""
Generate a valid json entry for the influxdb.write_points method
:param measurement: name of measurement
:param value: value to be stored
:param timestamp: string in the format "2009-11-10T23:00:00.0Z".
:return: dict - json structure
"""
result = {
"measurement": MyInfluxDBClient.escape_name(measurement),
"tags": {},
"time": timestamp,
"fields": {
"value": value
}
}
return result
@staticmethod
def _to_influx_timestamp(ht, epoch=datetime.datetime(1970, 1, 1)):
"""datatime cannot convert a datetimestring with nanoseconds"""
dt = datetime.datetime.strptime(ht[:-4], '%Y-%m-%dT%H:%M:%S.%f')
nanoseconds = int(ht[-4:-1])
td = dt - epoch
result = (td.microseconds + (td.seconds + td.days * 86400) * 10 ** 6)
result = result * 10 ** 3 + nanoseconds
return result
def write_point(self, measurement, value, timestamp=None):
"""
Write a single measurement value to the database (wrapper for influxdb.write_points method).
:param measurement: name of measurement
:param value: value to be stored
:param timestamp: string in the format "2009-11-10T23:00:00.0Z". if None is provided, the current time is used.
"""
if timestamp is None:
timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ") # "2009-11-10T23:00:00.0Z"
json_body = [
self._get_json_entry(measurement, value, timestamp)
]
self._logger.info("Write a point: (measurement: {}, timestamp: {}, value: {})".
format(measurement, timestamp, value))
self._logger.debug("Json: {}.".format(json_body))
self.client.write_points(json_body)
def write_points(self, measurement, entries):
"""
Write a list of entries (timestamp, value) into the measurement of the database. A timestamp must be a string
with the format "2009-11-10T23:00:00.0Z".
:param measurement: name of measurement
:param entries: list of (value, timestamp) tuples
"""
json_body = []
for entry in entries:
value, timestamp = entry
json_body.append(self._get_json_entry(measurement, value, timestamp))
self._logger.info("Write {} points to measurement {}.".
format(len(entries), measurement))
self._logger.debug("value/timestamp tuples: {}".format(entries))
self._logger.debug("Json: {}.".format(json_body))
self.client.write_points(json_body)
@staticmethod
def escape_name(name):
# https://stackoverflow.com/questions/47273602/how-to-insert-store-a-string-value-in-influxdb-measurement
name = name.replace(" ", "\ ")
name = name.replace(",", "\,")
return name
|
Archippe
|
/Archippe-0.2.1.tar.gz/Archippe-0.2.1/archippe/myinfluxdbclient.py
|
myinfluxdbclient.py
|
from pelops.abstractmicroservice import AbstractMicroservice
from archippe.myinfluxdbclient import MyInfluxDBClient
from archippe.topic import Topic
from archippe.schema.schema import get_schema
import archippe
class DataPersistence(AbstractMicroservice):
"""
The main entry point for the data persistence service. Creates the Topic-instances and starts/stops them.
Yaml config:
data-persistence:
topics: # list of topics that should be persisted
- topic: /test/temperature
type: float # float, integer, string, boolean
- topic: /test/humidity
type: float # float, integer, string, boolean
topic-request-prefix: /dataservice/request # prefix for each topic to request historic data
topic-response-prefix: /dataservice/response # prefix for each topic to publish historic data
"""
_version = archippe.version # version of software
_influx_client = None # instance of the influxdb client
_topics = None # list of instances of archippe.Topic
def __init__(self, config, pubsub_client=None, logger=None, stdout_log_level=None, no_gui=None):
"""
Constructor.
:param config: config yaml structure
:param pubsub_client: instance of an mymqttclient (optional)
:param logger: instance of a logger (optional)
:param no_gui: if False create and control a ui instance
:param stdout_log_level: if set, a logging handler with target sys.stdout will be added
"""
AbstractMicroservice.__init__(self, config, "data-persistence", pubsub_client=pubsub_client, logger=logger,
logger_name=__name__, stdout_log_level=stdout_log_level, no_gui=no_gui)
self._influx_client = MyInfluxDBClient(self._config["influx"], self._logger)
prefix_request = self._config["topic-request-prefix"]
prefix_response = self._config["topic-response-prefix"]
self._topics = []
for c in self._config["topics"]:
topic_sub = c["topic"]
if c["type"].lower() == "integer":
conversion = int
elif c["type"].lower() == "float":
conversion = float
elif c["type"].lower() == "boolean":
conversion = bool
elif c["type"].lower() == "string":
conversion = str
else:
self._logger.error("Unkown type '{}'.".format(c["type"]))
raise ValueError("Unkown type '{}'.".format(c["type"]))
topic = Topic(topic_sub, prefix_request + topic_sub, prefix_response + topic_sub, conversion, self._pubsub_client,
self._logger, self._influx_client)
self._topics.append(topic)
def _start(self):
for topic in self._topics:
topic.start()
def _stop(self):
for topic in self._topics:
topic.stop()
@classmethod
def _get_schema(cls):
return get_schema()
@classmethod
def _get_description(cls):
return "Archippe is a data persistence micro service for pelops. It uses influxdb to store incoming values " \
"and publishes the history a series upon request."
def runtime_information(self):
return {}
def config_information(self):
return {}
def standalone():
"""Calls the static method DataPersistence.standalone()."""
DataPersistence.standalone()
if __name__ == "__main__":
DataPersistence.standalone()
|
Archippe
|
/Archippe-0.2.1.tar.gz/Archippe-0.2.1/archippe/datapersistence.py
|
datapersistence.py
|
import typer
import json
import os
import requests
import jsonschema
import tempfile
import shutil
from pathlib import Path
from src.utils.path_manager_singleton import PathManagerSingleton
# from src.utils.functions import verify_config_options
from src.utils.config_manager_singleton import ConfigManagerSingleton
from src.plantumlv2.pu_manager import render_pu, render_diff_pu
from src.core.bt_graph import BTGraph
from src.plantuml.fetch_git import fetch_git_repo
from astroid.manager import AstroidManager
import astroid
astroid.MANAGER = None
app = typer.Typer(add_completion=True)
@app.command()
def render(config_path: str = "archlens.json"):
config = read_config_file(config_path)
mt_path_manager = PathManagerSingleton()
mt_path_manager.setup(config)
am = _create_astroid()
g = BTGraph(am)
g.build_graph(config)
render_pu(g, config)
def _create_astroid():
am = AstroidManager()
am.brain["astroid_cache"] = {}
return am
@app.command()
def render_diff(config_path: str = "archlens.json"):
with tempfile.TemporaryDirectory() as tmp_dir:
print("Created temporary directory:", tmp_dir)
config = read_config_file(config_path)
fetch_git_repo(
tmp_dir, config["github"]["url"], config["github"]["branch"]
)
shutil.copyfile(config_path, os.path.join(tmp_dir, "archlens.json"))
config_git = read_config_file(os.path.join(tmp_dir, "archlens.json"))
path_manager = PathManagerSingleton()
path_manager.setup(config, config_git)
local_am = _create_astroid()
local_graph = BTGraph(local_am)
local_graph.build_graph(config)
# verify_config_options(config, g)
remote_am = _create_astroid()
remote_graph = BTGraph(remote_am)
remote_graph.build_graph(config_git)
# verify_config_options(config_git, g_git)
render_diff_pu(local_graph, remote_graph, config)
@app.command()
def init(config_path="./archlens.json"):
schema_url = "https://raw.githubusercontent.com/Perlten/MT-diagrams/master/config.template.json"
os.makedirs(os.path.dirname(config_path), exist_ok=True)
schema = requests.get(schema_url).json()
schema["name"] = os.path.basename(os.getcwd())
with open(config_path, "w") as outfile:
json.dump(schema, outfile, indent=4)
@app.command()
def create_action():
action_url = "https://raw.githubusercontent.com/Perlten/MT-diagrams/master/.github/workflows/pr-mt-diagrams.yml"
action_path = Path(".github/workflows/pr-mt-diagrams.yml")
typer.secho(f"Creating the action at {action_path}", fg="green")
action_path.parent.mkdir(parents=True, exist_ok=True)
action = requests.get(action_url).text
with open(action_path, "w") as f:
f.write(action)
def read_config_file(config_path):
schema_url = "https://raw.githubusercontent.com/Perlten/MT-diagrams/master/config.schema.json"
config = None
with open(config_path, "r") as f:
config = json.load(f)
schema = requests.get(schema_url).json()
if not os.getenv("MT_DEBUG"):
jsonschema.validate(instance=config, schema=schema)
config["_config_path"] = os.path.dirname(os.path.abspath(config_path))
config_manager = ConfigManagerSingleton()
config_manager.setup(config)
return config
def main():
app()
if __name__ == "__main__":
main()
|
Architectural-Lens
|
/Architectural_Lens-0.0.6-py3-none-any.whl/src/cli_interface.py
|
cli_interface.py
|
import astroid
from astroid.manager import AstroidManager
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from src.core.bt_module import BTModule
class BTFile:
label: str = ""
edge_to: list["BTFile"] = None
ast = None
module: "BTModule" = None
am: AstroidManager
def __init__(
self, label: str, module, am: AstroidManager, code_path: str = None
):
self.label = label
self.ast = None
self.am = am
if code_path is not None:
self.ast: astroid.Module = self.am.ast_from_module_name(code_path)
self.edge_to = []
self.module = module
@property
def file(self):
if self.ast:
return self.ast.file
return ""
@property
def uid(self):
if self.ast:
return self.ast.file
else:
return self.label
@property
def module_path(self) -> str:
if not self.ast:
return None
return "/".join(self.file.split("/")[:-1])
def __rshift__(self, other):
if isinstance(other, list):
existing_edges = set(
[edge.file for edge in self.edge_to if edge.file != ""]
)
new_node_list = filter(
lambda e: e.file not in existing_edges, other
)
self.edge_to.extend([node for node in new_node_list])
else:
edges = set([edge.file for edge in self.edge_to])
if other.file in edges:
return
self.edge_to.append(other)
def get_imported_modules(
ast: astroid.Module, root_location: str, am: AstroidManager
) -> list:
imported_modules = []
for sub_node in ast.body:
try:
if isinstance(sub_node, astroid.node_classes.ImportFrom):
sub_node: astroid.node_classes.ImportFrom = sub_node
module_node = am.ast_from_module_name(
sub_node.modname,
context_file=root_location,
)
imported_modules.append(module_node)
elif isinstance(sub_node, astroid.node_classes.Import):
for name, _ in sub_node.names:
try:
module_node = am.ast_from_module_name(
name,
context_file=root_location,
)
imported_modules.append(module_node)
except Exception:
continue
elif hasattr(sub_node, "body"):
imported_modules.extend(
get_imported_modules(sub_node, root_location, am)
)
except astroid.AstroidImportError:
continue
return imported_modules
|
Architectural-Lens
|
/Architectural_Lens-0.0.6-py3-none-any.whl/src/core/bt_file.py
|
bt_file.py
|
import astroid
import sys
import os
from src.core.bt_file import BTFile, get_imported_modules
from src.core.bt_module import BTModule
from astroid.manager import AstroidManager
class BTGraph:
DEFAULT_SETTINGS = {"diagram_name": "", "project": None}
root_module_location: str = None
target_project_base_location: str = None
root_module = None
base_module = None
am: AstroidManager = None
def __init__(self, am: AstroidManager) -> None:
self.am = am
def build_graph(self, config: dict):
config_path = config.get("_config_path")
self.root_module_location = os.path.join(
config_path, config.get("rootFolder")
)
self.target_project_base_location = config_path
sys.path.insert(0, config_path)
sys.path.insert(1, self.root_module_location)
bt_module_list: list[BTModule] = []
# Read all the python files within the project
file_list = self._get_files_recursive(self.root_module_location)
# Create modules and add them to module list (No relations between them yet)
for file in file_list:
try:
if not file.endswith("__init__.py"):
continue
bt_module = BTModule(file, self.am)
bt_module.add_files()
bt_module_list.append(bt_module)
except Exception as e:
print(e)
continue
# Add relations between the modules (parent and child nodes)
for module in bt_module_list:
for parent_module in bt_module_list:
if module == parent_module:
continue
if parent_module.path == os.path.dirname(module.path):
parent_module.child_module.append(module)
module.parent_module = parent_module
# Find the root node
self.root_module = next(
filter(lambda e: e.parent_module is None, bt_module_list)
)
self.base_module = self.root_module
# Add dependencies between all the files
btf_map = self.get_all_bt_files_map()
for bt_file in btf_map.values():
imported_modules = get_imported_modules(
bt_file.ast, self.target_project_base_location, self.am
)
bt_file >> [
btf_map[module.file]
for module in imported_modules
if module.file in btf_map
]
sys.path = sys.path[2:]
astroid.manager.AstroidManager().clear_cache()
self.am.clear_cache()
def get_bt_file(self, path: str) -> BTFile:
file_path = self.am.ast_from_module_name(path).file
bt_file = self.get_all_bt_files_map()[file_path]
return bt_file
def get_bt_module(self, path: str) -> BTModule:
path_list = path.split(".")[1:]
current_module = self.root_module
while path_list:
current_module = next(
filter(
lambda e: e.name == path_list[0],
current_module.child_module,
)
)
path_list.pop(0)
return current_module
def change_scope(self, path: str):
self.root_module = self.get_bt_module(path)
def get_all_bt_files_map(self) -> dict[str, BTFile]:
return {
btf.file: btf for btf in self.root_module.get_files_recursive()
}
def get_all_bt_modules_map(self) -> dict[str, BTModule]:
return {
btm.path: btm
for btm in self.root_module.get_submodules_recursive()
}
def _get_files_recursive(self, path: str) -> list[str]:
file_list = []
t = list(os.walk(path))
for root, _, files in t:
for file in files:
file_list.append(os.path.join(root, file))
return file_list
|
Architectural-Lens
|
/Architectural_Lens-0.0.6-py3-none-any.whl/src/core/bt_graph.py
|
bt_graph.py
|
import astroid
import os
from src.core.bt_file import BTFile
from astroid.manager import AstroidManager
class BTModule:
parent_module: "BTModule" = None
child_module: list["BTModule"] = None
name_if_duplicate_exists = None
file_list: list["BTFile"] = None
ast: astroid.Module = None
am: AstroidManager = None
def __init__(self, file_path: str, am: AstroidManager) -> None:
self.ast = am.ast_from_file(file_path)
self.child_module = []
self.file_list = []
self.am = am
print(f"analyzing {self.path}")
@property
def depth(self):
parents = self.get_parent_module_recursive()
return len(parents)
@property
def name(self):
return self.ast.name.split(".")[-1]
@property
def path(self):
return os.path.dirname(self.ast.file)
def add_files(self):
files = [
element
for element in os.listdir(self.path)
if element.endswith(".py")
]
for file in files:
bt_file = BTFile(
label=file.split("/")[-1], module=self, am=self.am
)
bt_file.ast = self.am.ast_from_file(os.path.join(self.path, file))
self.file_list.append(bt_file)
def get_files_recursive(self) -> list[BTFile]:
temp_file_list = self.file_list.copy()
for child_module in self.child_module:
temp_file_list.extend(child_module.get_files_recursive())
return temp_file_list
def get_submodules_recursive(self) -> list["BTModule"]:
submodule_list = self.child_module.copy()
for submodule in self.child_module:
submodule_list.extend(submodule.get_submodules_recursive())
return submodule_list
def get_parent_module_recursive(self):
if self.parent_module is None:
return []
parent_module_list = [self.parent_module]
parent_module_list.extend(
self.parent_module.get_parent_module_recursive()
)
return parent_module_list
def get_module_dependencies(self) -> set["BTModule"]:
dependencies = set()
for child in self.file_list:
dependencies.update(map(lambda e: e.module, child.edge_to))
return dependencies
def get_dependency_count(self, other: "BTModule"):
file_dependencies = other.file_list
files = [
edge for element in self.file_list for edge in element.edge_to
]
count = len(
[element for element in files if element in file_dependencies]
)
return count
|
Architectural-Lens
|
/Architectural_Lens-0.0.6-py3-none-any.whl/src/core/bt_module.py
|
bt_module.py
|
import os
from src.core.bt_module import BTModule
from pathlib import Path
import fileinput
import sys
from src.utils.path_manager_singleton import PathManagerSingleton
from src.utils.config_manager_singleton import ConfigManagerSingleton
# list of subdomains is a set of strings, could be:
# "test_project/tp_src/api"
# "test_project/tp_src/tp_core/tp_sub_core"
# this would give the 2 sub-systems starting at api and tp_sub_core and how/if they relate in a drawing
def plantuml_diagram_creator_sub_domains(
root_node,
diagram_name,
packages,
ignore_packages,
compare_graph_root,
root_folder,
path_view,
save_location="./",
):
create_directory_if_not_exist(save_location)
global root_module
root_module = root_folder
diagram_type = "package "
diagram_name = diagram_name.replace(" ", "_")
diagram_name_txt = ""
if compare_graph_root is not None:
diagram_name_txt = save_location + diagram_name + "diffView"
else:
diagram_name_txt = save_location + diagram_name
diagram_name_txt = diagram_name_txt + ".txt"
que: Queue[BTModule] = Queue()
que.enqueue(root_node)
# tracks paths of nodes, so we dont enter the same node twice, path is needed so we dont hit duplicates
node_tracker = {}
# keeps track of names so we dont duplicate name modules in the graph
name_tracker = {}
if os.path.exists(diagram_name_txt):
os.remove(diagram_name_txt)
# adding root to the drawing IF its meant to be in there
if check_if_module_should_be_in_filtered_graph(root_node, packages):
f = open(diagram_name_txt, "a")
f.write("@startuml \n")
f.write("skinparam backgroundColor GhostWhite" + "\n")
f.write(
"title **Title**: "
+ diagram_name
+ ". **Rootfolder**: "
+ root_folder
+ "\n"
)
f.close()
else:
f = open(diagram_name_txt, "a")
f.write("@startuml \n")
f.write("skinparam backgroundColor GhostWhite" + "\n")
f.write("title " + diagram_name + " \n")
f.close()
while not que.isEmpty():
curr_node: BTModule = que.dequeue()
# adds all modules we want in our subgraph
for child in curr_node.child_module:
if child.path not in node_tracker:
duplicate_name_check(name_tracker, child, node_tracker, None, True)
que.enqueue(child)
node_tracker[child.path] = child
name_tracker[child.name] = child
if not ignore_modules_check(ignore_packages, child.path):
if check_if_module_should_be_in_filtered_graph(child, packages):
config_manager = ConfigManagerSingleton()
package_color = config_manager.package_color
f = open(diagram_name_txt, "a")
f.write(
diagram_type
+ '"'
+ get_name_for_module_duplicate_checker(child, path_view)
+ f'"#{package_color}'
+ "\n"
)
f.close()
# adding all dependencies
que.enqueue(root_node)
node_tracker_dependencies = {}
dependencies_map = {}
while not que.isEmpty():
curr_node: BTModule = que.dequeue()
for child in curr_node.child_module:
if child.path not in node_tracker_dependencies:
que.enqueue(child)
node_tracker_dependencies[child.path] = True
dependencies: set[BTModule] = curr_node.get_module_dependencies()
name_curr_node = get_name_for_module_duplicate_checker(curr_node, path_view)
if not ignore_modules_check(ignore_packages, curr_node.path):
for dependency in dependencies:
if not ignore_modules_check(ignore_packages, dependency.path):
name_dependency = get_name_for_module_duplicate_checker(
dependency, path_view
)
if check_if_module_should_be_in_filtered_graph(
dependency, packages
) and check_if_module_should_be_in_filtered_graph(
curr_node, packages
):
# this if statement is made so that we dont point to ourselves
if name_curr_node != name_dependency:
# used to detect dependency changes
if name_curr_node in dependencies_map:
dependency_list: list = dependencies_map[name_curr_node]
dependency_list.append(dependency)
dependencies_map[name_curr_node] = dependency_list
else:
dependency_list = []
dependency_list.append(dependency)
dependencies_map[name_curr_node] = dependency_list
f = open(diagram_name_txt, "a")
f.write(
'"'
+ name_curr_node
+ '"'
+ "-->"
+ '"'
+ name_dependency
+ f'"{get_dependency_string(curr_node, dependency)}'
+ "\n"
)
f.close()
# here we decide if we are diff view
if compare_graph_root is not None:
diff_checker = False
##################################### #########################################
# this section finds modules and colors them green or red depending on if theyre old or new
que.enqueue(compare_graph_root)
bfs_node_tracker = {}
main_nodes = {}
while not que.isEmpty():
curr_node: BTModule = que.dequeue()
for child in curr_node.child_module:
if child.path not in bfs_node_tracker:
que.enqueue(child)
bfs_node_tracker[child.path] = True
if not ignore_modules_check(ignore_packages, child.path):
duplicate_name_check(
main_nodes, child, node_tracker, root_folder, True
)
if check_if_module_should_be_in_filtered_graph(child, packages):
main_nodes[child.name] = child
# this will be true, if the package has been deleted
if (
child.name not in name_tracker
and not ignore_modules_check(
ignore_packages, child.path
)
):
diff_checker = True
f = open(diagram_name_txt, "a")
f.write(
diagram_type
+ '"'
+ get_name_for_module_duplicate_checker(
child, path_view
)
+ '" #red'
+ "\n"
)
f.close()
for child in name_tracker.values():
# children from original graph
if check_if_module_should_be_in_filtered_graph(
child, packages
) and not ignore_modules_check(ignore_packages, child.path):
node: BTModule = child
name = node.name
if name not in main_nodes:
diff_checker = True
f = open(diagram_name_txt, "a")
f.write(
diagram_type
+ '"'
+ get_name_for_module_duplicate_checker(node, path_view)
+ '" #green'
+ "\n"
)
f.close()
##############################################################################
# this section finds Dependencies and colors them green or red depending on if theyre old or new
que.enqueue(compare_graph_root)
dependencies_map_main_graph = {}
node_tracker_dependencies = {}
while not que.isEmpty():
curr_node: BTModule = que.dequeue()
for child in curr_node.child_module:
if child.path not in node_tracker_dependencies:
que.enqueue(child)
node_tracker_dependencies[child.path] = True
if not ignore_modules_check(ignore_packages, curr_node.path):
name_curr_node = get_name_for_module_duplicate_checker(
curr_node, path_view
)
dependencies: set[BTModule] = curr_node.get_module_dependencies()
dependencies_map_main_graph[name_curr_node] = dependencies
list_of_red_dependencies = find_red_dependencies(
dependencies_map, name_curr_node, dependencies
)
for dependency in list_of_red_dependencies:
if not ignore_modules_check(ignore_packages, dependency.path):
name_dependency = get_name_for_module_duplicate_checker(
dependency, path_view
)
if check_if_module_should_be_in_filtered_graph(
dependency, packages
) and check_if_module_should_be_in_filtered_graph(
curr_node, packages
):
# this if statement is made so that we dont point to ourselves
if name_curr_node != name_dependency:
diff_checker = True
f = open(diagram_name_txt, "a")
f.write(
'"'
+ name_curr_node
+ '"'
+ "-->"
+ '"'
+ name_dependency
+ f'" #red {get_dependency_string(curr_node, dependency)}'
+ "\n"
)
f.close()
for dependency in dependencies_map:
# api, and a list of all its dependencies (from the base graph)
list_of_new_dependencies = dependencies_map[dependency]
list_of_old_dependencies = []
if dependency in dependencies_map_main_graph:
list_of_old_dependencies = dependencies_map_main_graph[dependency]
for dep in list_of_new_dependencies:
dep_name = get_name_for_module_duplicate_checker(dep, path_view)
if not path_view:
dep_name = dep.name
not_found_partner = True
for dep_old in list_of_old_dependencies:
if dep.name == dep_old.name:
not_found_partner = False
break
if not_found_partner:
diff_checker = True
for line in fileinput.input(diagram_name_txt, inplace=True):
print(
line.replace( # TOOD: this replace does not work
f'"{dependency}"-->"{dep_name}"',
f'"{dependency}"-->"{dep_name}" #green',
),
end="",
)
#########################################################################################################
# ends the uml
f = open(diagram_name_txt, "a")
f.write("@enduml")
f.close()
if compare_graph_root is not None and diff_checker:
create_file(diagram_name_txt)
elif compare_graph_root is None:
create_file(diagram_name_txt)
if not os.getenv("MT_DEBUG"):
os.remove(diagram_name_txt)
def find_red_dependencies(new_dependencies, node_name, old_dependencies: set[BTModule]):
res = []
if node_name not in new_dependencies:
for dependency in old_dependencies:
res.append(dependency)
else:
list_of_new_dep_graph = new_dependencies[node_name]
for dependency in old_dependencies:
not_found_partner = True
for new_dependency in list_of_new_dep_graph:
if dependency.name == new_dependency.name:
not_found_partner = False
break
if not_found_partner:
res.append(dependency)
return res
def create_file(name):
python_executable = sys.executable
plantuml_server = os.getenv(
"PLANTUML_SERVER_URL",
"https://mt-plantuml-app-service.azurewebsites.net/img/",
)
os.system(f"{python_executable} -m plantuml --server {plantuml_server} {name}")
def get_name_for_module_duplicate_checker(module: BTModule, path):
if path:
path_manager = PathManagerSingleton()
module_split = path_manager.get_relative_path_from_project_root(
module.path, True
)
module_split = module_split.replace("/", ".")
return module_split
if module.name_if_duplicate_exists is not None:
module.name_if_duplicate_exists = module.name_if_duplicate_exists.replace(
"/", "."
)
return module.name_if_duplicate_exists
return module.name
def duplicate_name_check(
node_names,
curr_node: BTModule,
path_tracker,
root_folder=None,
first=False,
):
if was_node_in_original_graph(curr_node, path_tracker, root_folder):
if not curr_node.name_if_duplicate_exists:
if curr_node.name in node_names:
curr_node_split = split_path(curr_node.path)
curr_node_name = curr_node_split[-2] + "/" + curr_node_split[-1]
curr_node.name_if_duplicate_exists = curr_node_name
else:
if first:
if curr_node.name in node_names:
curr_node_split = split_path(curr_node.path)
curr_node_name = curr_node_split[-2] + "/" + curr_node_split[-1]
curr_node.name_if_duplicate_exists = curr_node_name
def was_node_in_original_graph(node: BTModule, path_tracker, root_folder):
if root_folder:
for path in path_tracker.keys():
path_split = path.split(root_folder)[-1]
path_from_tracker = root_folder + path_split
node_split = node.path.split(root_folder)[-1]
path_from_node = root_folder + node_split
if path_from_tracker == path_from_node:
if len(split_path(path_from_tracker)) != 2:
return True
return False
def ignore_modules_check(list_ignore: list[str], module):
path_manager = PathManagerSingleton()
module = path_manager.get_relative_path_from_project_root(module, True)
for ignore_package in list_ignore:
if (
ignore_package.startswith("*")
and ignore_package.endswith("*")
and ignore_package[1:-1] in module
):
return True
if module.startswith(ignore_package):
return True
return False
def old_ignore_modules_check(list_ignore, module, root_folder):
index = module.rindex(root_folder)
module = module[index:]
for word in list_ignore:
if word != "":
firstChar = word[0]
lastChar = word[-1]
# remove any module with word in its path
if firstChar == "*" and lastChar == "*":
if word[1:-1] in module:
return True
else:
# you cant have the module named "core" for instance
split_mod = split_path(module)
if split_mod[-1] == word:
return True
# case for if you match directly on a path
# e.g if you type zeeguu/core, this would remove the zeeguu/core module
split_mod = split_path(module)
module = "/".join(split_mod[3:])
if word == module:
return True
return False
# tp_src/api
def check_if_allowed_module_is_root(allowed_module):
if type(allowed_module) == str:
if "/" in allowed_module:
splits = allowed_module.split("/")
if splits[0] == root_module and splits[1] == root_module:
return splits[0]
else:
if "/" in allowed_module["packagePath"]:
splits = allowed_module["packagePath"].split("/")
if splits[0] == root_module and splits[1] == root_module:
allowed_module["packagePath"] = splits[0]
return allowed_module
return allowed_module
def check_if_module_should_be_in_filtered_graph(module: BTModule, allowed_modules):
if len(allowed_modules) == 0:
return True
path_manager = PathManagerSingleton()
module_path = path_manager.get_relative_path_from_project_root(module.path)
for module_curr in allowed_modules:
module_curr = check_if_allowed_module_is_root(module_curr)
# this means that we allow all of the sub system, no depth
if type(module_curr) == str:
if module_curr in module_path:
return True
# if we get here, it means that it is a specified object, at which point we must check for depth
else:
path = module_curr["packagePath"]
depth = module_curr["depth"]
if path == module_path:
module.depth = depth
return True
else:
if module.parent_module is not None:
if module.parent_module.depth is not None:
if path in module_path:
if module.parent_module.depth > 0:
module.depth = module.parent_module.depth - 1
return True
return False
def create_directory_if_not_exist(path: str):
Path(path).mkdir(parents=True, exist_ok=True)
def split_path(path) -> list[str]:
directories = []
while True:
path, directory = os.path.split(path)
if directory:
directories.append(directory)
else:
if path:
directories.append(path)
break
directories.reverse()
return directories
def get_dependency_string(module: BTModule, dependency_module: BTModule):
config_manager = ConfigManagerSingleton()
if config_manager.show_dependency_count:
dependency_count = module.get_dependency_count(dependency_module)
return f": {dependency_count}"
return ""
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
queue = Queue()
|
Architectural-Lens
|
/Architectural_Lens-0.0.6-py3-none-any.whl/src/plantuml/plantuml_file_creator.py
|
plantuml_file_creator.py
|
from src.core.bt_module import BTModule
from src.plantumlv2.utils import get_pu_package_path_from_bt_package
from enum import Enum
from src.utils.config_manager_singleton import ConfigManagerSingleton
class EntityState(str, Enum):
DELETED = "#Red"
NEUTRAL = ""
CREATED = "#Green"
PACKAGE_NAME_SPLITTER = "."
class PuPackage:
name = ""
parent: "PuPackage" = None
sub_modules: list["PuPackage"] = None
state: EntityState = EntityState.NEUTRAL
pu_dependency_list: list["PuDependency"] = None
bt_package: BTModule = None
def __init__(self, bt_package: BTModule) -> None:
self.pu_dependency_list = []
self.name = PACKAGE_NAME_SPLITTER.join(
get_pu_package_path_from_bt_package(bt_package).split("/")
)
self.bt_package = bt_package
self.sub_modules = []
@property
def path(self):
return get_pu_package_path_from_bt_package(self.bt_package)
@property
def parent_path(self):
return get_pu_package_path_from_bt_package(
self.bt_package.parent_module
)
def setup_dependencies(self, pu_package_map: dict[str, "PuPackage"]):
bt_dependencies = self.bt_package.get_module_dependencies()
self.parent = pu_package_map.get(self.parent_path)
if self.parent:
self.parent.sub_modules.append(self)
for bt_package_dependency in bt_dependencies:
pu_path = get_pu_package_path_from_bt_package(
bt_package_dependency
)
if pu_path == self.path:
continue
try:
pu_package_dependency = pu_package_map[pu_path]
self.pu_dependency_list.append(
PuDependency(
self,
pu_package_dependency,
self.bt_package,
bt_package_dependency,
)
)
except Exception:
pass
def get_parent_list(self):
res = []
if self.parent is None:
return res
res.append(self.parent)
res.extend(self.parent.get_parent_list())
return res
def render_package(self) -> str:
config_manager = ConfigManagerSingleton()
state_str = self.state.value
if self.state == EntityState.NEUTRAL:
state_str = config_manager.package_color
return f'package "{self.name}" {state_str}'
def render_dependency(self) -> str:
return "\n".join(
[
pu_dependency.render()
for pu_dependency in self.pu_dependency_list
]
)
def filter_excess_packages_dependencies(
self, used_packages: set["PuPackage"]
):
for sub_module in self.sub_modules:
if sub_module not in used_packages:
sub_module.filter_excess_packages_dependencies(used_packages)
self.pu_dependency_list.extend(sub_module.pu_dependency_list)
for dependency in self.pu_dependency_list:
if dependency.to_package not in used_packages:
parent_list = dependency.to_package.get_parent_list()
for p in parent_list:
if p in used_packages:
dep = PuDependency(
self,
p,
dependency.from_bt_package,
dependency.to_bt_package,
)
self.pu_dependency_list.append(dep)
break
# change all from package to self
for dependency in self.pu_dependency_list:
dependency.from_package = self
# filter all dependencies pointing to self
self.pu_dependency_list = [
dependency
for dependency in self.pu_dependency_list
if dependency.to_package != self
and dependency.to_package in used_packages
]
# Makes sure that there is only one dependency per package
aggregate_dependency_map: dict[str, PuDependency] = {}
for dependency in self.pu_dependency_list:
if dependency.id not in aggregate_dependency_map:
aggregate_dependency_map[dependency.id] = dependency
else:
dep = aggregate_dependency_map[dependency.id]
dep.dependency_count += dependency.dependency_count
self.pu_dependency_list = list(aggregate_dependency_map.values())
def get_dependency_map(self) -> dict[str, "PuDependency"]:
return {
dependency.to_package.path: dependency
for dependency in self.pu_dependency_list
}
class PuDependency:
state: EntityState = EntityState.NEUTRAL
from_package: PuPackage = None
to_package: PuPackage = None
from_bt_package: BTModule = None
to_bt_package: BTModule = None
dependency_count = 0
def __init__(
self,
from_package: PuPackage,
to_package: PuPackage,
from_bt_package: BTModule,
to_bt_package: BTModule,
) -> None:
self.from_package = from_package
self.to_package = to_package
self.from_bt_package = from_bt_package
self.to_bt_package = to_bt_package
self.dependency_count = self.from_bt_package.get_dependency_count(
self.to_bt_package
)
@property
def id(self):
return f"{self.from_package.name}-->{self.to_package.name}"
def render(self) -> str:
config_manager = ConfigManagerSingleton()
dependency_count_str = ""
if config_manager.show_dependency_count:
dependency_count_str = f": {self.dependency_count}"
from_name = self.from_package.name
to_name = self.to_package.name
return f'"{from_name}"-->"{to_name}" {self.state.value} {dependency_count_str}'
|
Architectural-Lens
|
/Architectural_Lens-0.0.6-py3-none-any.whl/src/plantumlv2/pu_entities.py
|
pu_entities.py
|
import sys
from src.core.bt_graph import BTGraph
from src.plantumlv2.pu_entities import (
PACKAGE_NAME_SPLITTER,
EntityState,
PuPackage,
)
from src.plantumlv2.utils import get_pu_package_path_from_bt_package
import os
def render_pu(graph: BTGraph, config: dict):
views = _create_pu_graph(graph, config)
for view_name, pu_package_map in views.items():
if os.getenv("MT_DEBUG"):
dep_count = sum(
len(package.pu_dependency_list)
for package in pu_package_map.values()
)
package_count = len(list(pu_package_map.values()))
print("View name:", view_name)
print("Package count:", package_count)
print("Dependency count:", dep_count)
plant_uml_str = _render_pu_graph(
list(pu_package_map.values()), view_name, config
)
project_name = config["name"]
save_location = os.path.join(
config["saveLocation"], f"{project_name}-{view_name}"
)
_save_plantuml_str(save_location, plant_uml_str)
def render_diff_pu(
local_bt_graph: BTGraph, remote_bt_graph: BTGraph, config: dict
):
project_name = config["name"]
local_graph_views = _create_pu_graph(local_bt_graph, config)
remote_graph_views = _create_pu_graph(remote_bt_graph, config)
packages_to_skip_dependency_update = set()
for view_name, local_graph in local_graph_views.items():
diff_graph: list[PuPackage] = []
remote_graph = remote_graph_views[view_name]
# Created packages
for path, package in local_graph.items():
if path not in remote_graph:
package.state = EntityState.CREATED
for package_dependency in package.pu_dependency_list:
package_dependency.state = EntityState.CREATED
diff_graph.append(package)
# Deleted packages
for remote_path, remote_package in remote_graph.items():
if remote_path not in local_graph:
remote_package.state = EntityState.DELETED
for (
remote_package_dependencies
) in remote_package.pu_dependency_list:
remote_package_dependencies.state = EntityState.DELETED
diff_graph.append(remote_package)
local_graph[remote_path] = remote_package
packages_to_skip_dependency_update.add(remote_path)
# Change dependency state
for path, package in local_graph.items():
if (
path not in remote_graph
or path in packages_to_skip_dependency_update
):
continue # We have already dealt with this case above
local_dependency_map = package.get_dependency_map()
remote_dependency_map = remote_graph[path].get_dependency_map()
# Created dependencies
for dependency_path, dependency in local_dependency_map.items():
if dependency_path not in remote_dependency_map:
dependency.state = EntityState.CREATED
# Deleted dependencies
for (
remote_dependency_path,
remote_dependency,
) in remote_dependency_map.items():
if remote_dependency_path not in local_dependency_map:
remote_dependency.state = EntityState.DELETED
remote_dependency.from_package = package
remote_dependency.to_package = local_graph[
remote_dependency_path
] # Ensures that the package refs will be in the final graph
package.pu_dependency_list.append(remote_dependency)
diff_graph.append(package)
plant_uml_str = _render_pu_graph(diff_graph, view_name, config)
save_location = os.path.join(
config["saveLocation"], f"{project_name}-diff-{view_name}"
)
_save_plantuml_str(save_location, plant_uml_str)
def _handle_duplicate_name(pu_graph: list[PuPackage]):
for package in pu_graph:
package_name_split = package.path.split("/")
found_duplicate = False
for package_2 in pu_graph:
if package == package_2:
continue
package_2_name_split = package_2.path.split("/")
if package_2_name_split[-1] == package_name_split[-1]:
if len(package_name_split) >= len(package_2_name_split):
package.name = PACKAGE_NAME_SPLITTER.join(
package_name_split[-2:]
)
else:
package.name = package_name_split[-1]
found_duplicate = True
if not found_duplicate:
package.name = package_name_split[-1]
def _render_pu_graph(pu_graph: list[PuPackage], view_name, config):
view_config: dict = config["views"][view_name]
use_package_path_as_label = view_config.get("usePackagePathAsLabel", True)
if not use_package_path_as_label:
_handle_duplicate_name(pu_graph)
pu_package_string = "\n".join(
[pu_package.render_package() for pu_package in pu_graph]
)
pu_dependency_string = "\n".join(
[pu_package.render_dependency() for pu_package in pu_graph]
)
project_name = config.get("name", "")
title = f"{project_name}-{view_name}"
uml_str = f"""
@startuml
skinparam backgroundColor GhostWhite
title {title}
{pu_package_string}
{pu_dependency_string}
@enduml
"""
if os.getenv("MT_DEBUG"):
print(uml_str)
print("Program Complete")
return uml_str
def _save_plantuml_str(file_name: str, data: str):
os.makedirs(os.path.dirname(file_name), exist_ok=True)
with open(file_name, "w") as f:
f.write(data)
python_executable = sys.executable
plantuml_server = os.getenv(
"PLANTUML_SERVER_URL",
"https://mt-plantuml-app-service.azurewebsites.net/img/",
)
os.system(
f"{python_executable} -m plantuml --server {plantuml_server} {file_name}"
)
if os.path.exists(file_name):
os.remove(file_name)
def _create_pu_graph(
graph: BTGraph, config: dict
) -> dict[str, dict[str, PuPackage]]:
bt_packages = graph.get_all_bt_modules_map()
views = {}
for view_name, view in config["views"].items():
pu_package_map: dict[str, PuPackage] = {}
for bt_package in bt_packages.values():
pu_package = PuPackage(bt_package)
pu_package_map[pu_package.path] = pu_package
for pu_package in pu_package_map.values():
pu_package.setup_dependencies(pu_package_map)
pu_package_map = _filter_packages(pu_package_map, view)
views[view_name] = pu_package_map
return views
def _find_packages_with_depth(
package: PuPackage, depth: int, pu_package_map: dict[str, PuPackage]
):
bt_sub_packages = package.bt_package.get_submodules_recursive()
filtered_sub_packages = [
get_pu_package_path_from_bt_package(sub_package)
for sub_package in bt_sub_packages
if (sub_package.depth - package.bt_package.depth) <= depth
]
return [pu_package_map[p] for p in filtered_sub_packages]
def _filter_packages(
packages_map: dict[str, PuPackage], view: dict
) -> dict[str, PuPackage]:
packages = list(packages_map.values())
filtered_packages_set: set[PuPackage] = set()
# packages
for package_view in view["packages"]:
for package in packages:
filter_path = package_view
if isinstance(package_view, str):
if package.path.startswith(filter_path.replace(".", "/")):
filtered_packages_set.add(package)
if isinstance(package_view, dict):
filter_path = package_view["packagePath"].replace(".", "/")
view_depth = package_view["depth"]
if filter_path == "" and package.parent_path == ".":
filtered_packages_set.add(package)
depth_filter_packages = _find_packages_with_depth(
package, view_depth - 1, packages_map
)
filtered_packages_set.update(depth_filter_packages)
elif package.path == filter_path:
filtered_packages_set.add(package)
depth_filter_packages = _find_packages_with_depth(
package, view_depth, packages_map
)
filtered_packages_set.update(depth_filter_packages)
if len(view["packages"]) == 0:
filtered_packages_set = set(packages_map.values())
# ignorePackages
updated_filtered_packages_set: set = set()
for ignore_packages in view["ignorePackages"]:
for package in filtered_packages_set:
should_filter = False
if ignore_packages.startswith("*") and ignore_packages.endswith(
"*"
):
if ignore_packages[1:-1] in package.path:
should_filter = True
else:
if package.path.startswith(ignore_packages):
should_filter = True
if not should_filter:
updated_filtered_packages_set.add(package)
if len(view["ignorePackages"]) == 0:
updated_filtered_packages_set = filtered_packages_set
filtered_packages_set = updated_filtered_packages_set
for package in filtered_packages_set:
package.filter_excess_packages_dependencies(filtered_packages_set)
return {package.path: package for package in filtered_packages_set}
|
Architectural-Lens
|
/Architectural_Lens-0.0.6-py3-none-any.whl/src/plantumlv2/pu_manager.py
|
pu_manager.py
|
# Archiv Viewer
Autor: Julian Hartig (c) 2020
Diese Software wird in Kombination mit Medical Office der Firma Indamed verwendet. Sie beseitigt den Nachteil,
dass eine gleichzeitige Anzeige von Archivdokumenten und Verwendung des Krankenblattes nicht möglich ist.
Außerdem wird ein PDF-Export der Archivdokumente angeboten.
Funktionsweise: Die angeklickten Archiveinträge werden im Hintergrund in eine PDF-Datei konvertiert, die dann im
PDF-Anzeigeprogramm, das als Systemstandard hinterlegt ist, angezeigt werden.
Beim PDF-Export werden alle oder die ausgewählten Dokumente in ein Sammel-PDF exportiert, welches dann weitergegeben
oder gedruckt werden kann.
|
ArchivViewer
|
/ArchivViewer-3.tar.gz/ArchivViewer-3/README.md
|
README.md
|
import sys, codecs, os, fdb, json, tempfile, shutil, subprocess, io, winreg, configparser
from datetime import datetime, timedelta
from collections import OrderedDict
from contextlib import contextmanager
from pathlib import Path
from lhafile import LhaFile
from PyPDF2 import PdfFileMerger
import img2pdf
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QFileDialog
from PyQt5.QtCore import QAbstractTableModel, Qt, QThread, pyqtSignal, pyqtSlot, QObject, QMutex, QTranslator, QLocale, QLibraryInfo
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from archivviewer.forms import ArchivviewerUi
exportThread = None
def parseBlobs(blobs):
entries = {}
for blob in blobs:
offset = 0
totalLength = int.from_bytes(blob[offset:offset+2], 'little')
offset += 4
entryCount = int.from_bytes(blob[offset:offset+2], 'little')
offset += 2
while offset < len(blob):
entryLength = int.from_bytes(blob[offset:offset+2], 'little')
offset += 2
result = parseBlobEntry(blob[offset:offset+entryLength])
entries[result['categoryId']] = result['name']
offset += entryLength
return OrderedDict(sorted(entries.items()))
def parseBlobEntry(blob):
offset = 6
name_length = int.from_bytes(blob[offset:offset+2], 'little')
offset += 2
name = blob[offset:offset+name_length-1].decode('cp1252')
offset += name_length
catid = int.from_bytes(blob[-2:], 'little')
return { 'name': name, 'categoryId': catid }
def displayErrorMessage(msg):
QMessageBox.critical(None, "Fehler", str(msg))
class ArchivViewer(QMainWindow, ArchivviewerUi):
def __init__(self, parent = None):
super(ArchivViewer, self).__init__(parent)
self.setupUi(self)
self.setWindowTitle("Archiv Viewer")
class FileChangeHandler(FileSystemEventHandler):
def __init__(self, gdtfile, model):
super().__init__()
self.gdtfile = gdtfile
self.model = model
def on_modified(self, event):
if self.gdtfile == event.src_path:
infos = readGDT(self.gdtfile)
try:
patid = int(infos["id"])
self.model.setActivePatient(infos)
except TypeError:
pass
class PdfExporter(QObject):
progress = pyqtSignal(int)
completed = pyqtSignal(int, str)
error = pyqtSignal(str)
kill = pyqtSignal()
def __init__(self, model, filelist, destination, parent=None):
super(PdfExporter, self).__init__(parent)
self.model = model
self.files = filelist
self.destination = destination
def work(self):
self.model.exportAsPdfThread(self, self.files, self.destination)
self.kill.emit()
class ArchivTableModel(QAbstractTableModel):
_startDate = datetime(1890, 1, 1)
def __init__(self, con, tmpdir, librepath, mainwindow, application):
super(ArchivTableModel, self).__init__()
self._files = []
self._categories = []
self._con = con
self._tmpdir = tmpdir
self._librepath = librepath
self._table = mainwindow.documentView
self._av = mainwindow
self._application = application
self._infos = {}
self.exportThread = None
self.mutex = QMutex(mode=QMutex.Recursive)
def __del__(self):
if self.exportThread:
self.exportThread.wait()
@contextmanager
def lock(self, msg=None):
if msg:
pass
self.mutex.lock()
yield
if msg:
pass
self.mutex.unlock()
def setActivePatient(self, infos):
with self.lock("setActivePatient"):
self._infos = infos
self._av.patientName.setText('{name}, {surname} [{id}]'.format(**infos))
self.reloadData(int(infos["id"]))
def data(self, index, role):
if role == Qt.DisplayRole:
with self.lock("setActivePatient"):
file = self._files[index.row()]
col = index.column()
if col == 0:
return file["datum"].strftime('%d.%m.%Y')
elif col == 1:
return file["datum"].strftime('%H:%M')
elif col == 2:
try:
return self._categories[file["category"]]
except KeyError:
return file["category"]
elif col == 3:
return file["beschreibung"]
def rowCount(self, index):
with self.lock("rowCount"):
return len(self._files)
def columnCount(self, index):
return 4
def headerData(self, section, orientation, role):
# section is the index of the column/row.
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
if section == 0:
return "Datum"
elif section == 1:
return "Zeit"
elif section == 2:
return "Kategorie"
elif section == 3:
return "Beschreibung"
def reloadData(self, patnr):
self._application.setOverrideCursor(Qt.WaitCursor)
self.beginResetModel()
self.reloadCategories()
self._files = []
selectStm = "SELECT a.FSUROGAT, a.FTEXT, a.FEINTRAGSART, a.FZEIT, a.FDATUM FROM ARCHIV a WHERE a.FPATNR = ? ORDER BY a.FDATUM DESC, a.FZEIT DESC"
cur = self._con.cursor()
cur.execute(selectStm, (patnr,))
for (surogat, beschreibung, eintragsart, zeit, datum) in cur:
self._files.append({
'id': surogat,
'datum': self._startDate + timedelta(days = datum, seconds = zeit),
'beschreibung': beschreibung,
'category': eintragsart
})
del cur
self.endResetModel()
self._table.resizeColumnsToContents()
self._table.horizontalHeader().setStretchLastSection(True)
self._application.restoreOverrideCursor()
def reloadCategories(self):
cur = self._con.cursor()
cur.execute("SELECT s.FKATEGORIELISTE, s.FABLAGELISTE, s.FBRIEFKATEGORIELISTE FROM MOSYSTEM s")
for blobs in cur:
self._categories = parseBlobs(blobs)
break
del cur
def generateFile(self, rowIndex, errorSlot = None):
with self.lock("generateFile"):
file = self._files[rowIndex]
filename = self._tmpdir + os.sep + '{}.pdf'.format(file["id"])
if not os.path.isfile(filename):
selectStm = "SELECT a.FDATEI FROM ARCHIV a WHERE a.FSUROGAT = ?"
cur = self._con.cursor()
cur.execute(selectStm, (file["id"],))
(datei,) = cur.fetchone()
merger = PdfFileMerger()
ios = None
try:
contents = datei.read()
ios = io.BytesIO(contents)
except:
ios = io.BytesIO(datei)
lf = LhaFile(ios)
for name in lf.namelist():
content = lf.read(name)
if content[0:5] == b'%PDF-':
merger.append(io.BytesIO(content))
elif content[0:5] == b'{\\rtf':
with tempdir() as tmpdir:
tmpfile = tmpdir + os.sep + "temp.rtf"
pdffile = tmpdir + os.sep + "temp.pdf"
with open(tmpfile, "wb") as f:
f.write(content)
command = '"'+" ".join(['"'+self._librepath+'"', "--convert-to pdf", "--outdir", '"'+tmpdir+'"', '"'+tmpfile+'"'])+'"'
if os.system(command) == 0:
try:
with open(pdffile, "rb") as f:
merger.append(io.BytesIO(f.read()))
except:
if errorSlot:
errorSlot.emit("Fehler beim Öffnen der konvertierten PDF-Datei '%s'" % (pdffile))
else:
displayErrorMessage("Fehler beim Öffnen der konvertierten PDF-Datei '%s'" % (pdffile))
else:
if errorSlot:
errorSlot.emit("Fehler beim Ausführen des Kommandos: '%s'" % (command))
else:
displayErrorMessage("Fehler beim Ausführen des Kommandos: '%s'" % (command))
elif name == "message.eml":
# eArztbrief
eml = email.message_from_bytes(content)
for part in eml.get_payload():
fnam = part.get_filename()
partcont = part.get_payload(decode=True)
if partcont[0:5] == b'%PDF-':
print("eArztbrief: hänge Anhang '%s' an den Export an" % (fnam))
merger.append(io.BytesIO(partcont))
else:
print("eArztbrief: nicht unterstütztes Anhangsformat in Anhang '%s'" % (fnam))
else:
try:
merger.append(io.BytesIO(img2pdf.convert(content)))
except Exception as e:
print("Dateiinhalt '%s' ist kein unterstützter Dateityp -> wird nicht an PDF angehängt (%s)" % (name, e))
merger.write(filename)
merger.close()
try:
datei.close()
except:
pass
ios.close()
return filename
def displayFile(self, rowIndex):
self._application.setOverrideCursor(Qt.WaitCursor)
filename = self.generateFile(rowIndex)
self._application.restoreOverrideCursor()
subprocess.run(['start', filename], shell=True)
def exportAsPdfThread(self, thread, filelist, destination):
self._application.setOverrideCursor(Qt.WaitCursor)
with self.lock("exportAsPdfThread"):
files = list(self._files)
try:
merger = PdfFileMerger()
counter = 0
filelist = sorted(filelist)
for file in filelist:
counter += 1
thread.progress.emit(counter)
filename = self.generateFile(file, errorSlot = thread.error)
bmtext = " ".join([files[file]["beschreibung"], files[file]["datum"].strftime('%d.%m.%Y %H:%M')])
merger.append(filename, bookmark=bmtext)
merger.write(destination)
merger.close()
except IOError as e:
thread.error.emit("Fehler beim Schreiben der PDF-Datei: {}".format(e))
thread.progress.emit(0)
self._application.restoreOverrideCursor()
thread.completed.emit(counter, destination)
return counter
def updateProgress(self, value):
self._av.exportProgress.setFormat('%d von %d' % (value, self._av.exportProgress.maximum()))
self._av.exportProgress.setValue(value)
def exportCompleted(self, counter, destination):
self._av.exportProgress.setFormat('')
self._av.exportProgress.setEnabled(False)
self._av.exportPdf.setEnabled(True)
self._av.documentView.setEnabled(True)
QMessageBox.information(None, "Export abgeschlossen", "%d Dokumente wurden nach '%s' exportiert" % (counter, destination))
def handleError(self, msg):
displayErrorMessage(msg)
def exportAsPdf(self, filelist):
if len(filelist) == 0:
buttonReply = QMessageBox.question(self._av, 'PDF-Export', "Kein Dokument ausgewählt. Export aus allen Dokumenten des Patienten erzeugen?", QMessageBox.Yes | QMessageBox.No)
if(buttonReply == QMessageBox.Yes):
with self.lock("exportAsPdf (filelist)"):
filelist = range(len(self._files))
else:
return
dirconfpath = os.sep.join([os.environ["AppData"], "ArchivViewer", "config.json"])
outfiledir = str(Path.home())
try:
with open(dirconfpath, "r") as f:
conf = json.load(f)
outfiledir = conf["outfiledir"]
except:
pass
outfilename = os.sep.join([outfiledir, 'Patientenakte_%d_%s_%s_%s-%s.pdf' % (int(self._infos["id"]),
self._infos["name"], self._infos["surname"], self._infos["birthdate"], datetime.now().strftime('%Y%m%d%H%M%S'))])
destination, _ = QFileDialog.getSaveFileName(self._av, "Auswahl als PDF exportieren", outfilename, "PDF-Datei (*.pdf)")
if len(destination) > 0:
try:
os.makedirs(os.path.dirname(dirconfpath), exist_ok = True)
with open(dirconfpath, "w") as f:
json.dump({ 'outfiledir': os.path.dirname(destination) }, f, indent = 1)
except:
pass
self._av.exportPdf.setEnabled(False)
self._av.documentView.setEnabled(False)
self._av.exportProgress.setEnabled(True)
self._av.exportProgress.setRange(0, len(filelist))
self._av.exportProgress.setFormat('0 von %d' % (len(filelist)))
self.pdfExporter = PdfExporter(self, filelist, destination)
self.exportThread = QThread()
self.pdfExporter.moveToThread(self.exportThread)
self.pdfExporter.kill.connect(self.exportThread.quit)
self.pdfExporter.progress.connect(self.updateProgress)
self.pdfExporter.completed.connect(self.exportCompleted)
self.pdfExporter.error.connect(self.handleError)
self.exportThread.started.connect(self.pdfExporter.work)
self.exportThread.start()
def readGDT(gdtfile):
grabinfo = {
3000: "id",
3101: "name",
3102: "surname",
3103: "birthdate"
}
infos = {
"id": None,
"name": None,
"surname": None
}
with codecs.open(gdtfile, encoding="iso-8859-15", mode="r") as f:
for line in f:
linelen = int(line[:3])
feldkennung = int(line[3:7])
inhalt = line[7:linelen - 2]
if feldkennung in grabinfo:
infos[grabinfo[feldkennung]] = inhalt
return infos
@contextmanager
def tempdir(prefix='tmp'):
"""A context manager for creating and then deleting a temporary directory."""
tmpdir = tempfile.mkdtemp(prefix=prefix)
try:
yield tmpdir
finally:
shutil.rmtree(tmpdir)
def tableDoubleClicked(table, model):
row = table.currentIndex().row()
if row > -1:
model.displayFile(row)
def exportSelectionAsPdf(table, model):
global exportThread
indexes = table.selectionModel().selectedRows()
files = []
for idx in indexes:
files.append(idx.row())
model.exportAsPdf(files)
def main():
app = QApplication(sys.argv)
qt_translator = QTranslator()
qt_translator.load("qt_" + QLocale.system().name(),
QLibraryInfo.location(QLibraryInfo.TranslationsPath))
app.installTranslator(qt_translator)
qtbase_translator = QTranslator()
qt_translator.load("qtbase_" + QLocale.system().name(),
QLibraryInfo.location(QLibraryInfo.TranslationsPath))
app.installTranslator(qtbase_translator)
try:
mokey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\WOW6432Node\\INDAMED')
defaultClientLib = os.sep.join([winreg.QueryValueEx(mokey, 'DataPath')[0], '..', 'Firebird', 'bin', 'fbclient.dll'])
except OSError as e:
displayErrorMessage("Failed to open Medical Office registry key: {}".format(e))
sys.exit()
conffile = os.getcwd() + os.sep + "Patientenakte.cnf"
conffile2 = os.path.dirname(os.path.realpath(__file__)) + os.sep + "Patientenakte.cnf"
try:
rstservini = configparser.ConfigParser()
rstservini.read(os.sep.join([os.environ["SYSTEMROOT"], 'rstserv.ini']))
defaultHost = rstservini["SYSTEM"]["Computername"]
defaultDb = os.sep.join([rstservini["MED95"]["DataPath"], "MEDOFF.GDB"])
except Exception as e:
displayErrorMessage("Failed to open rstserv.ini: {}".format(e))
sys.exit()
defaultDbUser = "sysdba"
defaultDbPassword = "masterkey"
defaultLibrePath = "C:\Program Files\LibreOffice\program\soffice.exe"
for cfg in [conffile, conffile2]:
try:
print("Attempting config %s" % (cfg))
with open(cfg, 'r') as f:
conf = json.load(f)
if "dbuser" in conf:
defaultDbUser = conf["dbuser"]
if "dbpassword" in conf:
defaultDbPassword = conf["dbpassword"]
if "libreoffice" in conf:
defaultLibrePath = conf["libreoffice"]
break
except Exception as e:
print("Failed to load config: %s." % (e))
print("Client lib is %s" % (defaultClientLib))
print("DB Path is %s on %s" % (defaultDb, defaultHost))
try:
print("Connecting db")
con = fdb.connect(host=defaultHost, database=defaultDb,
user=defaultDbUser, password=defaultDbPassword, fb_library_name=defaultClientLib)
print("Connection established.")
except Exception as e:
displayErrorMessage('Fehler beim Verbinden mit der Datenbank: {}'.format(e))
sys.exit()
try:
cur = con.cursor()
stm = "SELECT FVARVALUE FROM MED95INI WHERE FCLIENTNAME=? AND FVARNAME='PatexportDatei'"
cur.execute(stm, (os.environ["COMPUTERNAME"],))
res = cur.fetchone()
if res is None:
raise Exception("Keine Konfiguration für den Namen '{}' hinterlegt!".format(os.environ["COMPUTERNAME"]))
gdtfile = res[0][:-1].decode('windows-1252')
del cur
if not os.path.isdir(os.path.dirname(gdtfile)):
raise Exception("Ungültiger Pfad: '{}'. Bitte korrekten Pfad für Patientenexportdatei im Datenpflegesystem konfigurieren.".format(gdtfile))
except Exception as e:
displayErrorMessage("Fehler beim Feststellen des Exportpfades: {}".format(e))
sys.exit()
with tempdir() as myTemp:
av = ArchivViewer()
tm = ArchivTableModel(con, myTemp, defaultLibrePath, av, app)
av.documentView.doubleClicked.connect(lambda: tableDoubleClicked(av.documentView, tm))
av.documentView.setModel(tm)
av.exportPdf.clicked.connect(lambda: exportSelectionAsPdf(av.documentView, tm))
event_handler = FileChangeHandler(gdtfile, tm)
av.action_quit.triggered.connect(lambda: app.quit())
av.action_about.triggered.connect(lambda: QMessageBox.about(av, "Über Archiv Viewer",
"""<p><b>Archiv Viewer</b> ist eine zur Verwendung mit Medical Office der Fa. Indamed entwickelte
Software, die synchron zur Medical Office-Anwendung die gespeicherten Dokumente eines Patienten im Archiv
anzeigen kann. Zusätzlich können ausgewählte Dokumente auch als PDF-Datei exportiert werden.</p><p>(c) 2020 Julian Hartig - Lizensiert unter den Bedingungen der GPLv3</p>"""))
observer = Observer()
observer.schedule(event_handler, path=os.path.dirname(gdtfile), recursive=False)
observer.start()
try:
infos = readGDT(gdtfile)
tm.setActivePatient(infos)
except Exception as e:
print("While loading GDT file: %s" % (e))
av.show()
ret = app.exec_()
observer.stop()
if exportThread:
exportThread.stop()
exportThread.join()
observer.join()
sys.exit(ret)
|
ArchivViewer
|
/ArchivViewer-3.tar.gz/ArchivViewer-3/archivviewer/archivviewer.py
|
archivviewer.py
|
==============
python-archive
==============
This package provides a simple, pure-Python interface for handling various
archive file formats. Currently, archive extraction is the only supported
action. Supported file formats include:
* Zip formats and equivalents: ``.zip``, ``.egg``, ``.jar``.
* Tar and compressed tar formats: ``.tar``, ``.tar.gz``, ``.tgz``,
``.tar.bz2``, ``.tz2``.
Example usage
=============
Using the ``Archive`` class::
from archive import Archive
a = Archive('files.tar.gz')
a.extract()
Using the ``extract`` convenience function::
from archive import extract
# Extract in current directory.
extract('files.tar.gz')
# Extract in directory 'unpack_dir'.
extract('files.tar.gz', 'unpack_dir')
Note that calling extract with ``safe=True`` will ensure that the archive is
safe prior to extraction: ``UnsafeArchive`` exception will be raised when
archive contains paths which would be extracted outside of the target
directory (e.g. absolute paths)::
# Safely extract in directory 'unpack_dir'.
extract('files.tar.gz', 'unpack_dir', safe=True)
Similar tools
=============
* http://pypi.python.org/pypi/patool/ - portable command line archive file
manager.
* http://pypi.python.org/pypi/gocept.download/ - zc.buildout recipe for
downloading and extracting an archive.
|
Archive
|
/Archive-0.3.tar.gz/Archive-0.3/README.txt
|
README.txt
|
import os
import tarfile
import zipfile
class ArchiveException(Exception):
"""Base exception class for all archive errors."""
class UnrecognizedArchiveFormat(ArchiveException):
"""Error raised when passed file is not a recognized archive format."""
class UnsafeArchive(ArchiveException):
"""Error raised when passed file contains absolute paths which could be
extracted outside of the target directory."""
def extract(path, to_path='', safe=False, filename=None):
"""
Unpack the tar or zip file at the specified path to the directory
specified by to_path.
"""
Archive(path, filename).extract(to_path, safe)
class Archive(object):
"""
The external API class that encapsulates an archive implementation.
"""
def __init__(self, file, filename=None):
self._archive = self._archive_cls(file, filename)(file)
@staticmethod
def _archive_cls(file, filename=None):
cls = None
if not filename:
if isinstance(file, basestring):
filename = file
else:
try:
filename = file.name
except AttributeError:
raise UnrecognizedArchiveFormat(
"File object not a recognized archive format.")
base, tail_ext = os.path.splitext(filename.lower())
cls = extension_map.get(tail_ext)
if not cls:
base, ext = os.path.splitext(base)
cls = extension_map.get(ext)
if not cls:
raise UnrecognizedArchiveFormat(
"Path not a recognized archive format: %s" % filename)
return cls
def extract(self, to_path='', safe=False):
if safe:
to_abspath = os.path.abspath(to_path)
for name in self._archive.namelist():
dest = os.path.join(to_path, name)
if not os.path.abspath(dest).startswith(to_abspath):
raise UnsafeArchive("Unsafe destination path " \
"(outside of the target directory)")
self._archive.extract(to_path)
def namelist(self):
return self._archive.namelist()
def printdir(self):
self._archive.printdir()
class BaseArchive(object):
"""
Base Archive class. Implementations should inherit this class.
"""
def extract(self):
raise NotImplementedError
def namelist(self):
raise NotImplementedError
def printdir(self):
raise NotImplementedError
class TarArchive(BaseArchive):
def __init__(self, file):
self._archive = tarfile.open(file) if isinstance(file, basestring) \
else tarfile.open(fileobj=file)
def printdir(self, *args, **kwargs):
self._archive.list(*args, **kwargs)
def namelist(self, *args, **kwargs):
return self._archive.getnames(*args, **kwargs)
def extract(self, to_path=''):
self._archive.extractall(to_path)
class ZipArchive(BaseArchive):
def __init__(self, file):
self._archive = zipfile.ZipFile(file)
def printdir(self, *args, **kwargs):
self._archive.printdir(*args, **kwargs)
def namelist(self, *args, **kwargs):
return self._archive.namelist(*args, **kwargs)
def extract(self, to_path='', safe=False):
self._archive.extractall(to_path)
extension_map = {
'.egg': ZipArchive,
'.jar': ZipArchive,
'.tar': TarArchive,
'.tar.bz2': TarArchive,
'.tar.gz': TarArchive,
'.tgz': TarArchive,
'.tz2': TarArchive,
'.zip': ZipArchive,
}
|
Archive
|
/Archive-0.3.tar.gz/Archive-0.3/archive/__init__.py
|
__init__.py
|
import os
import shutil
import tempfile
import unittest
from archive import Archive, extract, UnsafeArchive, UnrecognizedArchiveFormat
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
class BaseArchiveTester(object):
archive = None
def setUp(self):
"""
Create temporary directory for testing extraction.
"""
self.tmpdir = tempfile.mkdtemp()
self.archive_path = os.path.join(TEST_DIR, self.archive)
# Always start off in TEST_DIR.
os.chdir(TEST_DIR)
def tearDown(self):
"""
Clean up temporary directory.
"""
shutil.rmtree(self.tmpdir)
def check_files(self, tmpdir):
self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, '1')))
self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, '2')))
self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, 'foo', '1')))
self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, 'foo', '2')))
self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, 'foo', 'bar', '1')))
self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, 'foo', 'bar', '2')))
class ArchiveTester(BaseArchiveTester):
def test_extract_method(self):
Archive(self.archive).extract(self.tmpdir)
self.check_files(self.tmpdir)
def test_extract_method_fileobject(self):
f = open(self.archive)
Archive(f).extract(self.tmpdir)
self.check_files(self.tmpdir)
def test_extract_method_no_to_path(self):
os.chdir(self.tmpdir)
Archive(self.archive_path).extract()
self.check_files(self.tmpdir)
def test_extract_function(self):
extract(self.archive_path, self.tmpdir)
self.check_files(self.tmpdir)
def test_extract_function_fileobject(self):
f = open(self.archive_path)
extract(f, self.tmpdir)
self.check_files(self.tmpdir)
def test_extract_function_no_to_path(self):
os.chdir(self.tmpdir)
extract(self.archive_path)
self.check_files(self.tmpdir)
def test_namelist_method(self):
l = Archive(self.archive).namelist()
expected = [
'1',
'2',
'foo',
'foo/1',
'foo/2',
'foo/bar',
'foo/bar/1',
'foo/bar/2']
if self.archive != 'foobar.zip':
# namelist result contains '.' except for the zip file
expected.insert(0, '.')
self.assertEqual([os.path.relpath(p) for p in l], expected)
class EvilArchiveTester(BaseArchiveTester):
def test_extract_method(self):
self.assertRaises(UnsafeArchive, Archive(self.archive).extract,
self.tmpdir, safe=True)
def test_extract_method_fileobject(self):
f = open(self.archive)
self.assertRaises(UnsafeArchive, Archive(f).extract, self.tmpdir,
safe=True)
def test_extract_method_no_to_path(self):
os.chdir(self.tmpdir)
self.assertRaises(UnsafeArchive, Archive(self.archive_path).extract,
safe=True)
def test_extract_function(self):
self.assertRaises(UnsafeArchive, extract, self.archive_path,
self.tmpdir, safe=True)
def test_extract_function_fileobject(self):
f = open(self.archive_path)
self.assertRaises(UnsafeArchive, extract, f, self.tmpdir, safe=True)
def test_extract_function_no_to_path(self):
os.chdir(self.tmpdir)
self.assertRaises(UnsafeArchive, extract, self.archive_path, safe=True)
def test_namelist_method(self):
l = Archive(self.archive).namelist()
expected = ['../../../../../../etc/passwd']
self.assertEqual([os.path.relpath(p) for p in l], expected)
class NoExtArchiveTester(BaseArchiveTester):
def test_constructor(self):
self.assertRaises(UnrecognizedArchiveFormat, Archive, self.archive)
def test_extract_method_filename(self):
Archive(self.archive, filename=self.filename).extract(self.tmpdir)
self.check_files(self.tmpdir)
def test_extract_function_filename(self):
extract(self.archive_path, self.tmpdir, filename=self.filename)
self.check_files(self.tmpdir)
class TestZip(ArchiveTester, unittest.TestCase):
archive = 'foobar.zip'
class TestEvilZip(EvilArchiveTester, unittest.TestCase):
archive = 'evil.zip'
class TestTar(ArchiveTester, unittest.TestCase):
archive = 'foobar.tar'
class TestGzipTar(ArchiveTester, unittest.TestCase):
archive = 'foobar.tar.gz'
class TestGzipTarNoExt(NoExtArchiveTester, unittest.TestCase):
archive = 'foobar_targz'
filename = 'foobar.tar.gz'
class TestZipNoExt(NoExtArchiveTester, unittest.TestCase):
archive = 'foobar_zip'
filename = 'foobar.zip'
class TestEvilGzipTar(EvilArchiveTester, unittest.TestCase):
archive = 'evil.tar.gz'
class TestBzip2Tar(ArchiveTester, unittest.TestCase):
archive = 'foobar.tar.bz2'
|
Archive
|
/Archive-0.3.tar.gz/Archive-0.3/archive/test/__init__.py
|
__init__.py
|
``ArchiveNews 0.2 (Beta)``
=======
A module that allows you to get and analyze news from `Arquivo.pt <https://arquivo.pt/>`_
Main Features
^^^^^^^
* Get Past Covers from Newspapers
* Get Past News from Newspapers
* Get Deep Data from the News (Title, Snippet, Link, Author, Date, Locations, Organizations, People and Keywords)
* Analysis the News
Usage (Python)
^^^^^^^
How to use it on Python
``1. Install the Module``::
pip install git+https://github.com/diogocorreia01/ArchiveNews.git
``2. Get the Covers``::
Get_Covers(years=[2013], output_path='Samples\\CoverSample.json', newspaper_url='https://www.publico.pt')
``3. Get the News``::
Get_News(input_file='Samples\\CoverSample.json', newspaper_url='https://www.publico.pt/', news_htmlTag='article', news_htmlClass='hentry', titles_htmlTag='h2', titles_htmlClass='entry-title', snippets_htmlTag='div',
snippets_htmlClass='entry-summary', links_htmlTag='a', links_htmlClass='href', authors_htmlTag='span', authors_htmlClass='fn', output_path='Samples\\NewsSample')
``4. Get the News Data``::
Get_News_Data(Samples\\NewsSample.json, Samples\\NewsDataSample)
Related projects
^^^^^^^
``Arquivo Publico`` -
|
ArchiveNews
|
/ArchiveNews-0.2.tar.gz/ArchiveNews-0.2/README.rst
|
README.rst
|
Copyright (c) 2012-2022 Scott Chacon and others
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
ArchiveNews
|
/ArchiveNews-0.2.tar.gz/ArchiveNews-0.2/LICENSE.rst
|
LICENSE.rst
|
import sys
DEFAULT_VERSION = "0.6c11"
DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
md5_data = {
'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
'setuptools-0.6c10-py2.3.egg': 'ce1e2ab5d3a0256456d9fc13800a7090',
'setuptools-0.6c10-py2.4.egg': '57d6d9d6e9b80772c59a53a8433a5dd4',
'setuptools-0.6c10-py2.5.egg': 'de46ac8b1c97c895572e5e8596aeb8c7',
'setuptools-0.6c10-py2.6.egg': '58ea40aef06da02ce641495523a0b7f5',
'setuptools-0.6c11-py2.3.egg': '2baeac6e13d414a9d28e7ba5b5a596de',
'setuptools-0.6c11-py2.4.egg': 'bd639f9b0eac4c42497034dec2ec0c2b',
'setuptools-0.6c11-py2.5.egg': '64c94f3bf7a72a13ec83e0b24f2749b2',
'setuptools-0.6c11-py2.6.egg': 'bfa92100bd772d5a213eedd356d64086',
'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',
'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',
'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',
'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03',
'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a',
'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6',
'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a',
}
import sys, os
try: from hashlib import md5
except ImportError: from md5 import md5
def _validate_md5(egg_name, data):
if egg_name in md5_data:
digest = md5(data).hexdigest()
if digest != md5_data[egg_name]:
print >>sys.stderr, (
"md5 validation of %s failed! (Possible download problem?)"
% egg_name
)
sys.exit(2)
return data
def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
download_delay=15
):
"""Automatically find/download setuptools and make it available on sys.path
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end with
a '/'). `to_dir` is the directory where setuptools will be downloaded, if
it is not already available. If `download_delay` is specified, it should
be the number of seconds that will be paused before initiating a download,
should one be required. If an older version of setuptools is installed,
this routine will print a message to ``sys.stderr`` and raise SystemExit in
an attempt to abort the calling script.
"""
was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
def do_download():
egg = download_setuptools(version, download_base, to_dir, download_delay)
sys.path.insert(0, egg)
import setuptools; setuptools.bootstrap_install_from = egg
try:
import pkg_resources
except ImportError:
return do_download()
try:
pkg_resources.require("setuptools>="+version); return
except pkg_resources.VersionConflict, e:
if was_imported:
print >>sys.stderr, (
"The required version of setuptools (>=%s) is not available, and\n"
"can't be installed while this script is running. Please install\n"
" a more recent version first, using 'easy_install -U setuptools'."
"\n\n(Currently using %r)"
) % (version, e.args[0])
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return do_download()
except pkg_resources.DistributionNotFound:
return do_download()
def download_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay = 15
):
"""Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download attempt.
"""
import urllib2, shutil
egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
url = download_base + egg_name
saveto = os.path.join(to_dir, egg_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
from distutils import log
if delay:
log.warn("""
---------------------------------------------------------------------------
This script requires setuptools version %s to run (even to display
help). I will attempt to download it for you (from
%s), but
you may need to enable firewall access for this script first.
I will start the download in %d seconds.
(Note: if this machine does not have network access, please obtain the file
%s
and place it in this directory before rerunning this script.)
---------------------------------------------------------------------------""",
version, download_base, delay, url
); from time import sleep; sleep(delay)
log.warn("Downloading %s", url)
src = urllib2.urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = _validate_md5(egg_name, src.read())
dst = open(saveto,"wb"); dst.write(data)
finally:
if src: src.close()
if dst: dst.close()
return os.path.realpath(saveto)
def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
try:
import setuptools
except ImportError:
egg = None
try:
egg = download_setuptools(version, delay=0)
sys.path.insert(0,egg)
from setuptools.command.easy_install import main
return main(list(argv)+[egg]) # we're done here
finally:
if egg and os.path.exists(egg):
os.unlink(egg)
else:
if setuptools.__version__ == '0.0.1':
print >>sys.stderr, (
"You have an obsolete version of setuptools installed. Please\n"
"remove it from your system entirely before rerunning this script."
)
sys.exit(2)
req = "setuptools>="+version
import pkg_resources
try:
pkg_resources.require(req)
except pkg_resources.VersionConflict:
try:
from setuptools.command.easy_install import main
except ImportError:
from easy_install import main
main(list(argv)+[download_setuptools(delay=0)])
sys.exit(0) # try to force an exit
else:
if argv:
from setuptools.command.easy_install import main
main(argv)
else:
print "Setuptools version",version,"or greater has been installed."
print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
def update_md5(filenames):
"""Update our built-in md5 registry"""
import re
for name in filenames:
base = os.path.basename(name)
f = open(name,'rb')
md5_data[base] = md5(f.read()).hexdigest()
f.close()
data = [" %r: %r,\n" % it for it in md5_data.items()]
data.sort()
repl = "".join(data)
import inspect
srcfile = inspect.getsourcefile(sys.modules[__name__])
f = open(srcfile, 'rb'); src = f.read(); f.close()
match = re.search("\nmd5_data = {\n([^}]+)}", src)
if not match:
print >>sys.stderr, "Internal error!"
sys.exit(2)
src = src[:match.start(1)] + repl + src[match.end(1):]
f = open(srcfile,'w')
f.write(src)
f.close()
if __name__=='__main__':
if len(sys.argv)>2 and sys.argv[1]=='--md5update':
update_md5(sys.argv[2:])
else:
main(sys.argv[1:])
|
Archiver
|
/Archiver-0.2.2.tar.gz/Archiver-0.2.2/ez_setup.py
|
ez_setup.py
|
Manual
++++++
Archiver is a tool that takes a source directory and hardlinks or copies all the
files into an archive based on their SHA1 hash, storing their original paths in
an SQLite database and creating a browsable hardlink copy of the original
structure.
If you have lots of archive copies of the same files you can therefore run
archiver on each of them and it will only store one copy, whilst being able to
re-generate any of them.
Sometimes the directory structure of files gives useful information about their
content that you would like to track. For example, if you were archiving photo
taken by individual members of a group on a dive trip you might want to tag a
particular path with tags such as the event, the person whose photos they are
and that the files are photos. Archiver lets you add the sort of information as
*extras*. The files themselves therefore have all the extra metadata for all
the paths they represent.
The internal implementation is quite simple. You just specify a directory to
contain the archive and it has this structure:
``store``
``a4e8``
Files by SHA1 hash ...
``ef2b``
Files by SHA1 hash ...
...
``browse``
<source1>
None
Files and Directories ...
Version 1
Files and Directories ...
Version 2
Files and Directories ...
<source2>
Initial
Files and Directories ...
Backup
Files and Directories ...
...
...
``paths.db``
``copy_in_progress_<pid>``
The tables the data is stored in in the ``paths.db`` SQLite3 database looks like this:
file
uid
source__uid ForeignKey('source.uid')),
hash (SHA1)
path (never ends in a /)
modified
created
accessed
owner (UID)
group (GID)
permission (no handling of sticky bits)
size (in bytes)
link (rel path to link to if in same source)
directory
uid
path (always ends in a /)
modified
created
accessed
owner (UID)
group (GID)
permission (no handling of sticky bits)
source
uid
source
created
extra
uid (represents the uid of the thing having extras added, not the uid of the extra itself, so this is not a primarykey)
key
value
type (can be "int", "datetime" or "string")
The commands themselves are fully documented. Just run something like this to get help:
::
python -m archiver.command --help
python -m archiver.command add --help
etc
In the near future I may also implement:
``verify --skip-hashes``
Check that all the files referred to in the metadata really exits.
If ``--skip-hashes`` isn't present, the SHA1 hashes of all the files are
checked to see if they are correct. A report of failures will be produced, you
can then use the ``restore`` command to restore any missing or damaged files.
WARNING: Missing or damaged files may be a sign of hard disk failure, you may
want to backup your archive or replace your disk.
``redundancy``
See which files would need to be backed up again to be able to remove a source or version
``backup --where= --exclude= src dst``
Copy files from a store to another location, ignoring metadata changes other than size which would indicate an error.
Special support for symbolic links
==================================
Directory and file symlinks are both supported by archiver but are handled
slightly differntly. Under linux, symlinks can have owner and group permissions
set, but not file permissions, and you can't set modified or accessed times.
Archiver therefore only sets owner and group attributes on a restored symlink.
Symlinks to directories
-----------------------
When restoring a symlink to a directory from a store, archiver will create the
symlink with *whatever data the original had*. If the original contained a
relative path, the restored version would have a relative path. If that
relative path resolved to something outside the source it may now point to the
wrong object because the path the source restored to is not likely to be the
same as the original. If the original symlink was a hard coded path, it would
be the same path in the restored versions.
To avoid the risk of any problems you should avoid absolute paths in symlinks
to directories and avoid reltive paths to directories outside the source
itself.
.. note ::
You would have the same problems with copying and pasting the source
directory so these issues aren't archiver-specific. I'm just highlighting
some of the risks associated with symlinks in general.
Symlinks to files
-----------------
If the symlink is a relative path to another file within the source, the
restore will restore the symlink. Otherwise, the restore will restore a *copy
of the original file*. This means data doesn't get lost even if the symlink no
longer resolves in the restored location.
In either case, if you were to ``rsync`` your original source directory to a
restored copy of the same source using archive mode (``-a``), no files would be
transferred in either of these cases. Archiver is therefore at least as good as
``rsync`` in its symlink handling.
To test:
* Absolute symlink for directory and file.
|
Archiver
|
/Archiver-0.2.2.tar.gz/Archiver-0.2.2/doc/source/manual.rst
|
manual.rst
|
import os
import logging
import sys
from commandtool import Cmd, LoggingCmd, handle_command
from configconvert.internal import eval_import
from archiver.api import make_batch, merge, sizeof_fmt, migrate, extract, numof_fmt, compare
log = logging.getLogger(__name__)
#
# Commands
#
class AppArchiver(LoggingCmd):
option_spec = LoggingCmd.option_spec.copy()
option_spec.update(dict(
store = dict(
options = ['-s', '--store'],
help = 'path to the store to create or use',
metavar='STORE_PATH',
),
))
help = {
'summary': 'Archive sources of files and directories',
}
def run(self, cmd):
LoggingCmd.run(self, cmd)
if cmd.opts.get('store'):
if not os.path.exists(cmd.opts.store):
cmd.out("The source store directory %r is not present, creating it.", cmd.opts.store)
cmd['batch'] = make_batch(cmd.opts.store)
return 0
class Add(Cmd):
arg_spec=[
('DIR', 'Directory to add to the store'),
('NAME', 'Identifier for this source eg "Files 1 2002"'),
]
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
skip_revert_times = dict(
options = ['--skip-revert-times'],
help = 'don\'t reset accessed and modified times for files on the source filesystem, useful if you are adding files from a read-only filesystem like a CD-ROM for example, only works if not using --hardlink',
),
#continue_from_last = dict(
# options = ['--continue-from-last'],
# help = 'the previous add didn\'t finish so just continue from where it left off (hoping that nothing has changed and that the OS will return files in the same order as last time, could be risky)',
#),
hardlink = dict(
options = ['-l', '--hardlink'],
help = (
'use hardlinks to add the files to the store if possible. '
'CAUTION: this only works if your source is on the same '
'physical disc as the store and can be slightly faster for '
'very large files but it means the files added to the store '
'cannot be made read only as that would also modify the '
'permission of the originals; with this option if someone '
'changed the original file, the linked version in store '
'would be silently changed too but the change would not '
'be reflected in either the file\'s hash or the store '
'metadata which could lead to unexpected problems later; '
'only use this option if you know the source can\'t change, '
'and even then, only if write performance to your store is '
'an issue'
),
),
extras_function = dict(
options = ['--extras-function'],
help = (
'import path to a function that will decide how to add '
'extras to files added to the store eg. '
'`my.module:photo_extras\''
),
metavar='EXTRAS_FUNCTION',
),
)
help = {
'summary': 'add a source directory to the store',
}
def run(self, cmd):
if not hasattr(cmd, 'batch'):
cmd.out('ERROR: No store specified')
return 1
source_path = cmd.args[0]
source_name = cmd.args[1]
if not os.path.exists(source_path):
cmd.out("ERROR: directory `%s\' does not exist", source_path)
return 1
# See if the source already exists
if source_name in cmd.batch.metadata.source_list():
cmd.out('ERROR: Source %r already exists', source_name)
return 1
if cmd.opts.get('extras_function'):
try:
extras_function=eval_import(cmd.opts.extras_function)
except ImportError:
cmd.out('ERROR: Could not import the extras function %r', cmd.opts.extras_function)
return 1
else:
extras_function=None
results = cmd.batch.source_add(
source_path,
source_name,
hardlink=cmd.opts.hardlink,
extras_function=extras_function,
skip_revert_times=cmd.opts.skip_revert_times,
)
if results['errors']:
cmd.out("The following files could not be added:")
for error in results['errors']:
cmd.out(error, end='')
cmd.out("%s failure(s) in total", len(results['errors']))
cmd.out("Done")
class Update(Add):
option_spec = Add.option_spec.copy()
option_spec.update(dict(
skip_failures = dict(
options = ['--skip-failures'],
help = 'don\'t try to add any files which couldn\'t be added in previous attempts',
),
ignore_new_symlink_times = dict(
options = ['--ignore-new-symlink-times'],
help = 'if you are updating from a restored directory structure, symlink times will be wrong so you won\'t want to update them',
),
))
help = {
'summary': (
'update an existing source by adding new files, useful if there '
'was an error adding the source the first time; files present '
'in the store but no longer present in the filesystem are NOT '
'deleted from the store'
)
}
def run(self, cmd):
if not hasattr(cmd, 'batch'):
cmd.out('ERROR: No store specified')
return 1
source_path = cmd.args[0]
source_name = cmd.args[1]
if source_name not in cmd.batch.metadata.source_list():
cmd.out('ERROR: No such source %r, did you mean to use `add\'?', source_name)
return 1
if cmd.opts.has_key('extras_function'):
try:
extras_function=eval_import(cmd.opts.extras_function)
except ImportError:
cmd.out('ERROR: Could not import the extras function %r', cmd.opts.extras_function)
return 1
else:
extras_function=None
results = cmd.batch.source_add(
source_path,
source_name,
hardlink=cmd.opts.hardlink,
skip_failures=cmd.opts.skip_failures,
extras_function=extras_function,
skip_revert_times=cmd.opts.skip_revert_times,
ignore_new_symlink_times=cmd.opts.ignore_new_symlink_times,
update=True,
)
cmd.out('''Results
files: %s
stored successfully: %s
storage failed: %s
metadata added: %s
metadata replaced: %s
dirs: %s
metadata added: %s
metadata replaced: %s'''%tuple(results['stats'])
)
if results['errors']:
cmd.out("ERROR: The following %s files could not be added:", len(results['errors']))
for error in results['errors']:
cmd.out(" %s", error)
cmd.out("Done")
class ExtrasUpdate(Cmd):
arg_spec=[
(
'EXTRAS_FUNCTION',
(
'import path to a function that will decide how to add '
'extras to files added to the store eg. '
'`my.module:photo_extras\''
)
),
('SOURCE', 'Source name'),
('DIR', 'Directory where the source files can be found (in case the extras function needs to inspect them)'),
]
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
)
help = {
'summary': 'reapply extras based on the stored file and directory metadata',
}
def run(self, cmd):
if not hasattr(cmd, 'batch'):
cmd.out('ERROR: No store specified')
return 1
source_name = cmd.args[1]
if source_name not in cmd.batch.metadata.source_list():
cmd.out('ERROR: No such source %r', source_name)
return 1
try:
extras_function=eval_import(cmd.args[0])
except ImportError:
cmd.out('ERROR: Could not import the extras function %r', cmd.opts.extras_function)
return 1
cmd.batch.extras_update(
source_name,
extras_function=extras_function,
path=cmd.args[1],
)
cmd.out("Done")
class ExtrasShow(Cmd):
arg_spec=[
('SOURCE', 'Name of the source'),
('FILE_PATH', 'The path of file whose extras are to be listed'),
]
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
)
help = {
'summary': 'print a display of the extras for a file in particular source',
}
def run(self, cmd):
if not hasattr(cmd, 'batch'):
cmd.out('ERROR: No store specified')
return 1
source_name = cmd.args[0]
source__uid = cmd.batch.metadata.source_exists(source_name)
if not source__uid:
cmd.out('ERROR: No such source %r', source_name)
return 1
file__uid = cmd.batch.metadata._file__uid(
cmd.args[1],
source__uid,
)
extras = cmd.batch.metadata.extras(file__uid)
for name in extras:
cmd.out('%s: %s', name, extras[name])
class Sources(Cmd):
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
skip_stats = dict(
options = ['--no-stats'],
help = 'don\'t print size of the source, number of files or number of errors',
),
)
help = {
'summary': 'list all the sources in the store',
}
def run(self, cmd):
if not hasattr(cmd, 'batch'):
cmd.out('ERROR: No store specified')
return 1
sources = cmd.batch.metadata.source_list()
for source in sources:
if cmd.opts.skip_stats:
cmd.out(source)
else:
source__uid = cmd.batch.metadata.source_exists(source)
errors = cmd.batch.metadata.connection.execute("SELECT count(*) from file where source__uid=? and hash=''", source__uid).first()[0]
files = cmd.batch.metadata.connection.execute("SELECT count(*) from file where source__uid=?", source__uid).first()[0]
size = sizeof_fmt(cmd.batch.metadata.connection.execute('SELECT sum(size) from file where source__uid=?', source__uid).first()[0])
cmd.out(
"%s: %s %s file(s) %s error(s)",
source,
size,
files,
errors,
)
class Failures(Cmd):
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
skip_paths = dict(
options = ['--skip-paths'],
help = 'don\'t show individual failed paths',
),
skip_counts = dict(
options = ['--skip-counts'],
help = 'don\'t calculate error counts for each source, implies --skip-paths too',
),
)
help = {
'summary': 'list all files which couldn\'t be copied into the store',
}
def run(self, cmd):
if not hasattr(cmd, 'batch'):
cmd.out('ERROR: No store specified')
return 1
sources = cmd.batch.metadata.source_list()
sources_with_errors = [x for x in cmd.batch.metadata.connection.execute("SELECT distinct source__uid, source.name from file join source on file.source__uid = source.uid where hash=''")]
cmd.out(
"%s/%s source(s) with errors...",
len(sources_with_errors),
len(sources),
)
for source__uid, source in sources_with_errors:
if cmd.opts.skip_counts:
cmd.out(" %s", source)
else:
errors = [x for x in cmd.batch.metadata.connection.execute("SELECT path from file where source__uid=? and hash=''", source__uid)]
if errors:
cmd.out(" %s - %s errors(s)", source, len(errors))
if not cmd.opts.skip_paths:
for error in errors:
cmd.out(" %s", error.path)
class Stats(Cmd):
help = {
'summary': 'summary statistics',
}
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
)
def run(self, cmd):
if not hasattr(cmd, 'batch'):
cmd.out('ERROR: No store specified')
return 1
cmd.out(
"%s sources(s)",
cmd.batch.metadata.connection.execute('SELECT count(*) from source').first()[0],
end='',
)
num_files = cmd.batch.metadata.connection.execute('SELECT count(*) from file').first()[0]
cmd.out(
"comprised of %s files(s)",
numof_fmt(num_files),
end='',
)
cmd.out(
"and %s directories(s)",
numof_fmt(cmd.batch.metadata.connection.execute('SELECT count(*) from directory').first()[0]),
end='',
)
cmd.out(
"originally %s",
sizeof_fmt(cmd.batch.metadata.connection.execute('SELECT sum(size) from file').first()[0]),
end='',
)
num_objects = cmd.batch.metadata.connection.execute('select count(*) FROM (SELECT distinct hash from file)').first()[0]
cmd.out(
"stored as %s unique binary object(s) with %s duplicate(s)",
numof_fmt(num_objects),
numof_fmt(num_files-num_objects),
end='',
)
data = cmd.batch.metadata.connection.execute('select sum(size) FROM (SELECT hash, size, count(uid) from file group by hash, size)').first()[0]
metadata = os.stat(os.path.join(cmd.chain[-1].opts.store, 'paths.db')).st_size
cmd.out(
"and now using %s for the data and %s for metadata.",
sizeof_fmt(data),
sizeof_fmt(metadata),
end='',
)
class Files(Cmd):
help = {
'summary': 'print a list of files in a source',
}
arg_spec=[
('SOURCE_NAME', 'the name of the source'),
]
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
)
def run(self, cmd):
if not hasattr(cmd, 'batch'):
cmd.out('ERROR: No store specified')
return 1
source = cmd.args[0]
if not source in cmd.batch.metadata.source_list():
cmd.out("ERROR: No such source %r", source)
return 1
file_records = cmd.batch.metadata.file_list(source)
size = 0
for file in file_records:
size += file.size
# XXX This used to fail for Unicode files
cmd.out(u'%s %-9s %s', file.hash, sizeof_fmt(file.size), file.path)
cmd.out(
"%s file(s) in total with a generated size of %s",
len(file_records),
sizeof_fmt(size),
)
class Migrate(Cmd):
help = {
'summary': 'migrate a store to use a new version of archiver',
}
arg_spec=[
('SRC', 'store path to migrate from'),
('DST', 'store path to migrate to'),
('FROM', 'version number of the store at the moment'),
('TO', 'version to migrate to'),
]
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
)
def run(self, cmd):
migrate('%s->%s'%(cmd.args[2], cmd.args[3]), cmd.args[0], cmd.args[1])
cmd.out("Done.")
class BinaryUnique(Cmd):
help = {
'summary': 'print information about the number of unique binary files in a store from a particular source (not unique file paths)',
}
arg_spec=[
('SOURCE_NAME', 'the name of the source'),
]
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
)
def run(self, cmd):
if not hasattr(cmd, 'batch'):
cmd.out('ERROR: No store specified')
return 1
source = cmd.args[0]
if not source in cmd.batch.metadata.source_list():
cmd.out("ERROR: No such source %r", source)
return 1
unique_files = cmd.batch.unique_files(source)
size = 0
for file in unique_files:
cmd.out("%s %s", file.hash, file.path)
size += file.size
cmd.out(
"%s unique binary file(s) added to the store from the %r source, adding %s",
len(unique_files),
source,
sizeof_fmt(size),
)
class Diff(Cmd):
help = {
'summary': 'find files in a different metadata source that aren\'t present in this one',
}
arg_spec=[
('METADATA_PATH', 'the path to the folder containing the \'paths.db\' file to compare'),
]
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
no_size = dict(
options = ['--no-size'],
help = 'don\'t display the size in the output',
),
show_paths = dict(
options = ['--show-paths'],
help = 'show full paths to the objects, not just the hash',
),
)
def run(self, cmd):
if not hasattr(cmd, 'batch'):
cmd.out('ERROR: No store specified')
return 1
other = make_batch(cmd.args[0])
res = [x[0] for x in cmd.batch.metadata.connection.execute('select distinct hash from file')]
size = 0
if x:
unique = [(x[0], x[1]) for x in other.metadata.connection.execute('select distinct hash, size from file where hash not in (%s)'%(('? ,'*len(x))[:-2]), x)]
for hash_, size_ in unique:
if cmd.opts.show_paths:
path = os.path.join(cmd.args[0], hash_[:4]+'/'+hash_)
else:
path = hash_
if cmd.opts.no_size:
cmd.out(path)
else:
cmd.out("%s %s", path, size_)
size += size_
else:
unique = []
cmd.out(
"%s store object(s) are unique to %r",
len(unique),
#cmd.chain[-1].opts.store,
cmd.args[0],
)
if not cmd.opts.no_size:
cmd.out(
"Total size: %s",
sizeof_fmt(size),
)
class Remove(Cmd):
help = {
'summary': 'remove a source from the store, deleting its metadata and any files which aren\'t being used by other sources',
}
arg_spec=[
('SOURCE_NAME', 'the name of the source to delete'),
]
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
skip_files = dict(
options = ['--skip-files'],
help = 'don\'t remove the files from the store, just remove the source metadata',
),
)
def run(self, cmd):
if not hasattr(cmd, 'batch'):
cmd.out('ERROR: No store specified')
return 1
source = cmd.args[0]
if not source in cmd.batch.metadata.source_list():
cmd.out("ERROR: No such source %r", source)
return 1
unique_files, size = cmd.batch.source_remove(source, cmd.opts.skip_files)
cmd.out(
"Successfully removed metadata for %s",
source,
)
if not cmd.opts.skip_files:
if len(unique_files):
cmd.out(
"Also removed %s binary object files from the store freeing %s",
len(unique_files),
sizeof_fmt(size),
)
else:
cmd.out("No binary object files needed to be removed from the store")
class Restore(Cmd):
help = {
'summary': 'restore a source directory structure from the store',
}
arg_spec=[
('DST', 'where to start the directory structure'),
]
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
hardlink = dict(
options = ['--hardlink'],
help = 'instead of copying the files and setting the original permissions, just hardlink to the copy in the store to create a readonly restore',
),
update_file_metadata = dict(
options = ['--update-file-metadata'],
help = 'inspect existing files to see if their metadata needs reapplying',
),
update_directory_metadata = dict(
options = ['--update-directory-metadata'],
help = 're-apply metadata to directories',
),
source = dict(
options = ['--source'],
help = 'the name of the source to restore (can be specified multiple times, will restore all sources if no --source option is specified)',
multiple=True,
metavar='PATH',
),
)
def run(self, cmd):
if not hasattr(cmd, 'batch'):
cmd.out('ERROR: No store specified')
return 1
if cmd.opts.hardlink and cmd.opts.metadata:
cmd.out('ERROR: You cannot restore metadata if you are using the `--hardlink\' option')
return 1
if not cmd.opts.get('source'):
sources = cmd.batch.metadata.source_list()
else:
sources = cmd.opts.source
for source in sources:
cmd.out("Restoring %r to %r", source, cmd.args[0])
cmd.batch.restore(
cmd.args[0],
source,
hardlink=cmd.opts.hardlink,
update_file_metadata=cmd.opts.update_file_metadata,
update_directory_metadata=cmd.opts.update_directory_metadata,
)
cmd.out("Done.")
class Merge(Cmd):
arg_spec=[
('DST', 'path where the merged store should be created. eg `/arc/merge/store\''),
(1, 'path to one of the stores to merge', 'At least one stores must be specified', 'STORE'),
]
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
skip_files = dict(
options = ['--skip-files'],
help = 'if you are sure you have already copied all files into the new store you can skip the check, then only the metadata merge will occur',
),
allow_update = dict(
options = ['--update'],
help = 'merge into DST even if it already contains data, this will fail if any of the sources already have a source name present in the destination store',
),
)
help = {
'summary': 'merge one or more stores into a new store',
}
def run(self, cmd):
if not cmd.opts.allow_update and os.path.exists(os.path.join(cmd.args[0], 'paths.db')):
cmd.out(
"ERROR: destination %r already contains a `paths.db' file, use `--update' to update anyway",
cmd.args[0]
)
return 1
if not os.path.exists(cmd.args[0]):
os.mkdir(cmd.args[0])
for store in cmd.args[1:]:
if not os.path.exists(store):
cmd.out("ERROR: store %r does not exist", store)
return 1
if not os.path.isdir(store):
cmd.out("ERROR: store %r is not a directory", store)
return 1
merge(cmd.args[0], cmd.args[1:], cmd.opts.skip_files)
cmd.out("Done.")
class Extract(Cmd):
arg_spec=[
('SRC', 'path to the current store'),
('DST', 'path to the where the extracted store should be created'),
(1, 'names of one or more sources from the SRC store to extract', 'At least one source must be specified', 'SOURCE'),
]
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
skip_files = dict(
options = ['--skip-files'],
help = 'if you are sure you have already copied all files into the new store you can skip the check, then only the metadata merge will occur',
),
)
help = {
'summary': 'copy one or more sources from an existing store into a new one',
}
def run(self, cmd):
if os.path.exists(os.path.join(cmd.args[1], 'paths.db')):
cmd.out("ERROR: destination %r already contains a `paths.db' file", cmd.args[1])
return 1
if not os.path.exists(cmd.args[1]):
os.mkdir(cmd.args[1])
extract(cmd.args[0], cmd.args[1], cmd.args[2:], cmd.opts.skip_files)
cmd.out("Done.")
class Compare(Cmd):
arg_spec=[
('SRC', 'path to the source directory'),
('DST', 'path to the the directory to compare it to'),
]
option_spec = dict(
help = dict(
options = ['-h', '--help'],
help = 'display this message',
),
binary = dict(
options = ['--binary'],
help = 'compare the contents of files too',
),
)
help = {
'summary': 'compare one directory with another',
}
def run(self, cmd):
if not os.path.exists(cmd.args[0]):
cmd.out("ERROR: directory `%s\' does not exist", cmd.args[0])
return 1
if not os.path.exists(cmd.args[1]):
cmd.out("ERROR: directory `%s\' does not exist", cmd.args[1])
return 1
compare(cmd.args[0], cmd.args[1], cmd.opts.binary)
cmd.out("Done.")
from pipestack.app import pipe, command, App
class Archiver(App):
commands = [
command(None , AppArchiver ),
command('add' , Add ),
command('update' , Update ),
command('remove' , Remove ),
command('merge' , Merge ),
command('extract' , Extract ),
command('restore' , Restore ),
command('sources' , Sources ),
command('stats' , Stats ),
command('files' , Files ),
command('extras' , [
(None, Cmd),
('update', ExtrasUpdate),
('show', ExtrasShow),
]),
command('failures' , Failures ),
command('binary-unique', BinaryUnique),
command('diff' , Diff ),
command('compare' , Compare ),
command('migrate' , Migrate ),
]
if __name__ == '__main__':
Archiver().handle_command_line(program='python -m archiver.command')
|
Archiver
|
/Archiver-0.2.2.tar.gz/Archiver-0.2.2/archiver/command.py
|
command.py
|
import datetime
import hashlib
import os
import logging
import sys
import time
from subprocess import Popen
log = logging.getLogger(__name__)
def set_time(path, accessed, modified):
# This doesn't seem to work on directories
if isinstance(accessed, datetime.datetime):
accessed = time.mktime(accessed.timetuple())
if isinstance(modified, datetime.datetime):
modified = time.mktime(modified.timetuple())
if not isinstance(accessed, (int, float)):
raise Exception('Expected a datatime, int or float object to set the accessed time for %r, not %r'%(path, accessed))
if not isinstance(modified, (int, float)):
raise Exception('Expected a datatime, int or float object to set the modified time for %r, not %r'%(path, modified))
log.debug('Setting %r accessed time to %s and modified time to %s', path, accessed, modified)
os.utime(
path,
(
accessed,
modified,
)
)
# We use 16*1024 as the size because that's what shutil.copyfileobj() uses,
# so it should be a sensible default.
def sha1(src, size=16*1024, skip_revert_times=False):
log.debug('Generating a sha1 hash for %r', src)
h = hashlib.new('sha1')
stat_src = os.stat(src)
f = open(src, "rb")
try:
chunk = f.read(size)
while chunk: # EOF condition
h.update(chunk)
chunk = f.read(size)
except Exception, e:
log.error('Could not generate hash %r. Error was %r', src, e)
raise
else:
# Put the source time back to how it was. @@@ is this a good idea?
if not skip_revert_times:
try:
set_time(
src,
stat_src.st_atime,
stat_src.st_mtime,
)
except Exception, e:
log.error(
'Could not reset the modification time on %r. Error was %r',
src,
e,
)
return h.hexdigest()
finally:
f.close()
|
Archiver
|
/Archiver-0.2.2.tar.gz/Archiver-0.2.2/archiver/helper.py
|
helper.py
|
from __future__ import unicode_literals
import datetime
import hashlib
import logging
import os
import sys
import shutil
import time
import uuid
from bn import relpath, uniform_path, AttributeDict
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey,\
DateTime, Enum, select, and_, create_engine, not_
from sqlalchemy.sql import func
from archiver.helper import sha1, set_time
log = logging.getLogger(__name__)
#
# Schema
#
def schema2():
metadata = MetaData()
return AttributeDict(
metadata = metadata,
file_records = Table('file', metadata,
Column('uid', Integer, primary_key=True),
Column('source__uid', None, ForeignKey('source.uid')),
Column('hash', String),
Column('path', String), # Never ends in a /
Column('modified', DateTime),
Column('accessed', DateTime),
Column('owner', Integer),
Column('group', Integer),
Column('permission', Integer),
Column('size', Integer),
Column('link', String),
),
directory_records = Table('directory', metadata,
Column('uid', Integer, primary_key=True),
Column('source__uid', None, ForeignKey('source.uid')),
Column('path', String), # Always ends in a /
Column('modified', DateTime),
Column('accessed', DateTime),
Column('owner', Integer),
Column('group', Integer),
Column('permission', Integer),
Column('link', String),
),
source_records = Table('source', metadata,
Column('uid', Integer, primary_key=True),
Column('name', String),
Column('created', DateTime, default=datetime.datetime.now),
),
# No-one was using tag or file_tag so skipping those tables
)
metadata = MetaData()
file_records = Table('file', metadata,
Column('uid', String, primary_key=True),
Column('source__uid', None, ForeignKey('source.uid')),
Column('hash', String),
Column('path', String), # Never ends in a /
Column('modified', DateTime),
Column('accessed', DateTime),
Column('owner', Integer),
Column('group', Integer),
Column('permission', Integer),
Column('size', Integer),
Column('link', String),
)
directory_records = Table('directory', metadata,
Column('uid', String, primary_key=True),
Column('source__uid', None, ForeignKey('source.uid')),
Column('path', String), # Always ends in a /
Column('modified', DateTime),
Column('accessed', DateTime),
Column('owner', Integer),
Column('group', Integer),
Column('permission', Integer),
Column('link', String),
)
source_records = Table('source', metadata,
Column('uid', String, primary_key=True),
Column('name', String),
Column('created', DateTime, default=datetime.datetime.now),
)
extra_records = Table('extra', metadata,
# We can have duplicate uids for files
Column('uid', String),
Column('key', String),
Column('value', String),
Column('type', String),
)
#
# Helpers
#
try:
chmod = os.lchmod
except AttributeError:
chmod = os.chmod
log.debug('No os.lchmod found, using os.chmod instead')
def make_uid():
return str(uuid.uuid4())
def sizeof_fmt(num):
if num < 1024:
return '%s bytes'%num
for x in ['bytes','KB','MB','GB','TB']:
if num < 1024.0:
return "%3.1f%s" % (num, x)
num /= 1024.0
def numof_fmt(num):
result = []
num = str(num)
while len(num)>3:
result.append(num[-3:])
num = num[:-3]
if num:
result.append(num)
result.reverse()
return ','.join(result)
def to_date(string):
try:
return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S.%f")
except ValueError:
return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")
def time_now():
return str(datetime.datetime.now())[11:19]
def make_batch(store_path, md=metadata):
if not os.path.exists(store_path):
os.mkdir(store_path)
created=False
sqlite_path = os.path.join(store_path, 'paths.db')
if not os.path.exists(sqlite_path):
created=True
engine = create_engine('sqlite:///%s'%sqlite_path, echo=False)
md.create_all(engine)
connection = engine.connect()
if created:
log.info('Creating the directory index...')
connection.execute(''' create index directory_index on directory('source__uid', 'path')''')
log.info('Creating the file index...')
connection.execute(''' create index file_index on file('source__uid', 'path')''')
batch = Batch(
source = FileSystemSource(),
store = FileSystemStore(store_path),
metadata = SQLite3Metadata(connection),
)
return batch
def apply_metadata(path, permission, owner, group, accessed, modified):
os.lchown(path, owner, group)
if not os.path.islink(path):
# On linux we can't set the permissions or time of symbolic link
# directories, just their owner
chmod(path, permission)
set_time(path, accessed, modified)
# We use 16*1024 as the size because that's what shutil.copyfileobj() uses,
# so it should be a sensible default.
def copy_without_accessing(src, dst, size=16*1024, with_hash=False, skip_revert_times=False):
log.debug('Copying without accessing %r', src)
if with_hash:
h = hashlib.new('sha1')
stat_src = os.stat(src)
if os.path.exists(dst):
os.remove(dst)
f = open(src, "rb")
d = open(dst, "wb")
try:
chunk = f.read(size)
while chunk: # EOF condition
if with_hash:
h.update(chunk)
d.write(chunk)
chunk = f.read(size)
except Exception, e:
log.error('Could not copy %r. Error was %r', src, e)
raise
else:
# Put the source time back to how it was. @@@ is this a good idea?
if not skip_revert_times:
try:
set_time(
src,
stat_src.st_atime,
stat_src.st_mtime,
)
except Exception, e:
log.error(
'Could not reset the modification time on %r. Error was %r',
src,
e,
)
if with_hash:
return h.hexdigest()
finally:
f.close()
d.close()
#
# Global functionality
#
def migrate(step, src, dst):
if step=='1->2':
# This migration is mainly about removing the source_file and
# source_directory metadata tables. No-one has files in the
# old format now, could be removed.
# We don't migrate tags
src_engine = create_engine('sqlite:///%s'%src)
dst_batch = make_batch(dst)
files = []
for row in src_engine.execute('''
SELECT
source_file.uid,
source_file.source__uid,
file.hash,
file.path,
file.modified,
file.accessed,
file.owner,
file."group",
file.permission,
file.size,
file.link
FROM source_file
JOIN file ON source_file.file__uid = file.uid
'''):
res = dict(row)
res['accessed'] = to_date(res['accessed'])
res['modified'] = to_date(res['modified'])
files.append(res)
print 'f',
directories = []
for row in src_engine.execute('''
SELECT
source_directory.uid,
source_directory.source__uid,
directory.path,
directory.modified,
directory.accessed,
directory.owner,
directory."group",
directory.permission,
directory.link
FROM source_directory
JOIN directory ON source_directory.directory__uid = directory.uid
'''):
res = dict(row)
res['accessed'] = to_date(res['accessed'])
res['modified'] = to_date(res['modified'])
directories.append(res)
print 'd',
sources = []
for row in src_engine.execute('''
SELECT uid, name, created
FROM source
'''):
res = dict(row)
res['created'] = to_date(res['created'])
sources.append(res)
print 's',
trans = dst_batch.metadata.connection.begin()
try:
log.info('Copying sources...')
print 'sources'
dst_batch.metadata.connection.execute(
source_records.insert(),
sources,
)
print 'directories'
dst_batch.metadata.connection.execute(
directory_records.insert(),
directories,
)
print 'files'
dst_batch.metadata.connection.execute(
file_records.insert(),
files,
)
trans.commit()
except:
trans.rollback()
raise
print "Failed"
else:
print "Success"
elif step=='2->3':
# This migration is mainly about replacing tags with extras and using
# guids instead of ids for the uid. It roughly doubles the size of
# the database and halves the speed
old_schema = schema2()
src_batch = make_batch(src, md=old_schema.metadata)
dst_batch = make_batch(dst)
files = src_batch.metadata.connection.execute(
select([old_schema.file_records])
)
directories = src_batch.metadata.connection.execute(
select([old_schema.directory_records])
)
sources = src_batch.metadata.connection.execute(
select([old_schema.source_records])
)
trans = dst_batch.metadata.connection.begin()
try:
log.info('Updating sources...')
# Set the new source uids
source_mapper = dict()
for source in sources:
print 's',
source_mapper[source.uid] = source.name
data = dict(source)
data['source'] = data['name']
del data['name']
del data['uid']
dst_batch.metadata.source_add(**data)
for directory in directories:
print 'd',
data = dict(directory)
del data['uid']
data['source'] = source_mapper[data['source__uid']]
del data['source__uid']
dst_batch.metadata.directory_add(**data)
for file in files:
print 'f',
data = dict(file)
del data['uid']
data['source'] = source_mapper[data['source__uid']]
del data['source__uid']
data['hash_str'] = data['hash']
del data['hash']
dst_batch.metadata.file_add(**data)
trans.commit()
except:
trans.rollback()
print "Failed"
raise
else:
print "Success"
elif step=='3->4':
dst_batch = make_batch(src)
trans = dst_batch.metadata.connection.begin()
try:
log.info('Creating the directory index...')
trans.connection.execute(''' create index directory_index on directory('source__uid', 'path')''')
log.info('Creating the file index...')
trans.connection.execute(''' create index file_index on file('source__uid', 'path')''')
log.info('Committing...')
trans.commit()
except:
trans.rollback()
print "Failed"
raise
else:
print "Success"
elif step=='4->5':
# This removes duplicate files and directories in the source with ID 15afc8dd-d332-4be9-94a0-4e2b4eeef97c
dst_batch = make_batch(src)
trans = dst_batch.metadata.connection.begin()
try:
log.info('Finding all duplicate directories...')
to_delete = []
for dup_row in trans.connection.execute("""
select distinct path from directory
where source__uid='15afc8dd-d332-4be9-94a0-4e2b4eeef97c'
group by path having count(uid) > 1
"""):
uids = []
for row in trans.connection.execute("""
select distinct uid from directory
where source__uid='15afc8dd-d332-4be9-94a0-4e2b4eeef97c'
and path=?
""", (dup_row[0],)):
uids.append(row[0])
for item in uids[1:]:
to_delete.append(item)
num = 100
log.info('%s directory record(s) to delete', len(to_delete))
if to_delete and raw_input('Really delete [y/N] ').lower() =='y':
while len(to_delete):
chunk = to_delete[:num]
to_delete = to_delete[num:]
print ".",
trans.connection.execute(
"""
delete from directory
where uid in (%s)
"""%(('?,'*len(chunk))[:-1],),
tuple(chunk),
)
log.info('Finding all duplicate files...')
to_delete = []
all_ = []
for dup_row in trans.connection.execute("""
select distinct path from file
where source__uid='15afc8dd-d332-4be9-94a0-4e2b4eeef97c'
group by path having count(uid) > 1
"""):
res = trans.connection.execute("""
select * from file
where source__uid='15afc8dd-d332-4be9-94a0-4e2b4eeef97c'
and path=?
""", (dup_row[0],))
all_.append([x for x in res])
uids = []
for row in trans.connection.execute("""
select distinct uid from file
where source__uid='15afc8dd-d332-4be9-94a0-4e2b4eeef97c'
and path=?
""", (dup_row[0],)):
uids.append(row[0])
for item in uids[:-1]:
to_delete.append(item)
log.info('%s file record(s) to delete', len(to_delete))
print '\n'.join([str(x) for x in all_[:10]])
if to_delete and raw_input('Really delete [y/N] ').lower() =='y':
while len(to_delete):
chunk = to_delete[:num]
to_delete = to_delete[num:]
print ".",
trans.connection.execute(
"""
delete from file
where uid in (%s)
"""%(('?,'*len(chunk))[:-1],),
tuple(chunk),
)
log.info('Committing...')
trans.commit()
except:
trans.rollback()
print "Failed"
raise
else:
print "Success"
else:
raise Exception('Unknown step %s'%step)
def compare(src, dst, binary=False):
if binary:
os.system('diff -qru "%s" "%s"'%(src, dst))
else:
os.system('rsync -aHxv --numeric-ids --delete --dry-run -i "%s/" "%s/"'%(src, dst))
def extract(src, dst, sources, skip_files=False):
dst_batch = make_batch(dst)
copy_store_metadata(src, dst, sources)
if not skip_files:
hashes = [row[0] for row in dst_batch.metadata.connection.execute(
select(
[file_records.c.hash],
source_records.c.name.in_(sources),
from_obj=[
file_records.join(source_records),
],
).distinct()
)]
copy_store_data(src, dst, hashes)
def merge(dst, stores, skip_files=False):
file_counts = []
if uniform_path(dst) in [uniform_path(store) for store in stores]:
raise Exception('You can\'t merge %r into itself'%dst)
log.info(
"Querying stores to discover the number of files they represent...",
)
sqlite_path = os.path.join(dst, 'paths.db')
log.info(' Connecting to %s', 'sqlite:///%s'%sqlite_path)
engine = create_engine('sqlite:///%s'%sqlite_path, echo=False)
connection = engine.connect()
metadata.create_all(engine)
dst_sources = []
for source in connection.execute('SELECT name from source'):
dst_sources.append(source[0])
sources = []
for store in stores:
sqlite_path = os.path.join(store, 'paths.db')
log.info(' Connecting to %s', 'sqlite:///%s'%sqlite_path)
engine = create_engine('sqlite:///%s'%sqlite_path, echo=False)
connection = engine.connect()
result = connection.execute('SELECT count(*) from file')
num_source_files = result.first()[0]
log.info(' %s source files', num_source_files)
if not store == dst:
file_counts.append((num_source_files, store))
result = connection.execute('SELECT name from source')
for source_list in result:
if source_list[0] in dst_sources:
raise Exception(
'The merge target store already contains a store named '
'%r so you cannot merge %r into it' % (
source_list[0],
store,
)
)
if source_list[0] in sources:
raise Exception(
'Cannot merge because the source named %r exists in '
'two stores, please rename it or remove it from '
'one of them' % (
source_list[0],
)
)
else:
sources.append(source_list[0])
file_counts.sort()
if not dst_sources:
# We can copy an existing database as a starting point
path_to_use = os.path.join(file_counts[-1][1], 'paths.db')
log.info(
"Chosen %r as the base for the metadata merge later",
path_to_use,
)
if not skip_files:
log.info('Hardlinking files (store with the fewest files first)...')
counter = 0
for file_num, store in file_counts:
counter += 1
log.info(
" Copying store data for %s source files from "
" %r -> %r [%s/%s]",
file_num,
store,
dst,
counter,
len(file_counts),
)
copy_store_data(store, dst)
else:
log.info("File check skipped due to `--skip-files' option. [SKIP]")
log.info("Starting metadata merge...")
if not dst_sources:
log.info(
" Copying store database (%s files) from %r -> %r [1/%s]",
file_counts[-1][0],
file_counts[-1][1],
dst,
len(file_counts),
)
shutil.copy(
path_to_use,
os.path.join(dst, 'paths.db'),
)
left_to_merge = file_counts[:-1]
counter = 1
else:
left_to_merge = file_counts
counter = 0
for file_num, store in left_to_merge:
counter += 1
log.info(
" Copying store metadata (%s files) from %r -> %r [%s/%s]",
file_num,
store,
dst,
counter,
len(file_counts),
)
store_batch = make_batch(store)
copy_store_metadata(store, dst, store_batch.metadata.source_list())
def copy_store_metadata(store, dst, sources):
file_count = 0
next_file_print = 8
store_batch = make_batch(store)
dst_batch = make_batch(dst)
for source in sources:
data = store_batch.metadata.source(source)
trans = dst_batch.metadata.connection.begin()
try:
source__uid = dst_batch.metadata.source_add(source, data.created)
for directory_record in store_batch.metadata.directory_list(source):
log.debug(" Adding directory %s", directory_record.path)
directory_data = dict(directory_record)
del directory_data['uid']
del directory_data['source__uid']
dst_batch.metadata.directory_add(
source=source,
**directory_data
)
for file_record in store_batch.metadata.file_list(source):
file_count += 1
if file_count == next_file_print:
log.info(' Added metadata for %s files so far [%s]', file_count, time_now())
if next_file_print < 2000:
next_file_print = int(next_file_print * 1.3)
else:
next_file_print = file_count + 2000
extras=store_batch.metadata.extras(file_record.uid)
log.debug(" Adding file %s with extras %r", file_record.path, extras)
file_data = dict(file_record)
del file_data['uid']
del file_data['source__uid']
hash_str=file_data['hash']
del file_data['hash']
dst_batch.metadata.file_add(
source=source,
extras=extras,
hash_str=hash_str,
**file_data
)
trans.commit()
except:
trans.rollback()
raise
def copy_store_data(src, dst, hashes=None):
if not hashes:
hashes = []
log.info('Getting a list of all the hashes in the store...')
for root, dirs, files in os.walk(unicode(src)):
for filename in files:
if filename != 'paths.db':
hashes.append(filename)
log.info('Done.')
real_file_count = 0
linked_file_count = 0
next_file_print = 8
log.info('Hardlinking store files...')
for hash in hashes:
real_file_count += 1
if real_file_count == next_file_print:
log.info(' Checked %s files, %s linked so far [%s]', real_file_count, linked_file_count, time_now())
if next_file_print < 2000:
next_file_print = int(next_file_print * 1.3)
else:
next_file_print = file_count + 2000
dst_dir = os.path.join(dst, hash[:4])
if not os.path.exists(dst_dir):
os.mkdir(dst_dir)
src_file = os.path.join(src, hash[:4], hash)
dst_file = os.path.join(dst_dir, hash)
if not os.path.exists(dst_file):
log.debug(" File: %s -> %s", src_file, dst_file)
linked_file_count += 1
os.link(src_file, dst_file)
#
# Be able to archive files in a filesytem
#
class FileSystemSource(object):
def metadata(self, file_path):
stat = os.lstat(file_path) # This stats a symlink, not the file it points to
# We have st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime
if os.path.islink(file_path):
link = os.readlink(file_path)
else:
link = None
return dict(
modified = datetime.datetime.fromtimestamp(stat.st_mtime),
accessed = datetime.datetime.fromtimestamp(stat.st_atime),
owner = stat.st_uid,
group = stat.st_gid,
permission = stat.st_mode,
size = stat.st_size,
link = link,
)
#
# Store files by their hash in a filesystem
#
class FileSystemStore(object):
def __init__(self, store_path):
self.store_path = store_path
if not os.path.exists(store_path):
os.mkdir(store_path)
def add(
self,
source_path,
base_path,
hardlink=False,
hash_str=None,
skip_revert_times=False,
):
copy = True
src = os.path.join(base_path, source_path)
if hardlink:
copy = False
if os.path.islink(src):
#src = os.readlink(src)
#directory = '/'.join(os.path.split('/')[:-1])
src = os.path.abspath(os.path.join(os.path.split(os.path.abspath(src))[0], os.readlink(src)))
copy=True
#raise Exception('Code handling hardlinking to symlinks has not been tested, remove this exception to test it')
else:
if not hash_str:
hash_str = sha1(os.path.join(base_path, source_path), skip_revert_times=skip_revert_times)
store_dir = os.path.join(self.store_path, hash_str[0:4])
if not os.path.exists(store_dir):
os.mkdir(store_dir)
# Get the dst path to hardlink later in this function
dst = os.path.join(store_dir, hash_str)
if copy:
hash_str = copy_without_accessing(
src,
os.path.join(self.store_path, 'copy_in_progress_%s'%(os.getpid(),)),
with_hash = True,
skip_revert_times=skip_revert_times,
)
store_dir = os.path.join(self.store_path, hash_str[0:4])
if not os.path.exists(store_dir):
os.mkdir(store_dir)
dst = os.path.join(store_dir, hash_str)
if os.path.exists(dst):
log.info('File %r already exists in the store as %r', source_path, dst)
if copy:
# Remove the temporary file we created for the hash
os.remove(os.path.join(self.store_path, 'copy_in_progress_%s'%(os.getpid(),)))
else:
log.debug('File %r will be added to the store as %r', source_path, dst)
if hardlink:
# There is a chance here that the dst path is a relative symlink. We don't want to link to that, instead we want to link to the file the symlink resolves to
os.link(
src,
dst,
)
# @@@ Note we aren't changing the permissions here because
# that would affect the source files
else:
# Move the temp file into the store
os.rename(os.path.join(self.store_path, 'copy_in_progress_%s'%(os.getpid(),)), dst)
# Make the destination read and execute only
chmod(dst, 500)
return hash_str
def remove(self, h):
store_dir = os.path.join(self.store_path, h[0:4])
if not os.path.exists(os.path.join(store_dir, h)):
log.warning('Could not remove %r because it doesn\'t exist', os.path.join(store_dir, h))
else:
os.remove(os.path.join(store_dir, h))
if os.path.exists(store_dir) and os.path.isdir(store_dir) and not os.listdir(store_dir):
os.rmdir(store_dir)
#
# Store metadata in an SQLite3 database
#
class SQLite3Metadata(object):
def __init__(self, connection):
self.connection = connection
def file_update(
self,
uid,
path,
hash_str,
modified,
accessed,
owner,
group,
permission,
size,
source='default',
extras=None,
link=None,
):
# First delete the current file
self.connection.execute('DELETE from file WHERE uid = ?;', uid)
# Then add the new ones
return self.file_add(
path=path,
hash_str=hash_str,
modified=modified,
accessed=accessed,
owner=owner,
group=group,
permission=permission,
size=size,
source=source,
extras=extras,
link=link,
)
def file_add(
self,
path,
hash_str,
modified,
accessed,
owner,
group,
permission,
size,
source='default',
extras=None,
link=None,
):
source__uid = self.source_exists(source)
if source__uid is None:
source__uid = self.source_add(source)
if not isinstance(path, unicode):
raise Exception('Expected a unicode string for %r'%path)
file__uid = self.connection.execute(
file_records.insert().values(
uid=make_uid(),
source__uid=source__uid,
path=path,
hash=hash_str,
modified=modified,
accessed=accessed,
owner=owner,
group=group,
permission=permission,
size=size,
link=link,
)
).inserted_primary_key[0]
if extras is not None:
self.update_extras(file__uid, extras)
return file__uid
def update_extras(self, file__uid, extras):
# First delete any current extras
self.connection.execute('DELETE from extra WHERE uid = ?;', file__uid)
# Then add the new ones
if isinstance(extras, dict):
extras = extras.items()
for extra in extras:
d = {'uid': file__uid, 'key': extra[0], 'value': extra[1], 'type': len(extra)>2 and extra[2] or None}
self.connection.execute(
extra_records.insert().values(d)
)
def extras(self, file__uid):
result = {}
for extra in self.connection.execute(
select(
[extra_records],
and_(
extra_records.c.uid==file__uid,
),
)
):
value = extra.value
if extra.type:
if extra.type == 'int':
value=int(value)
elif extra.type == 'datetime':
value = to_date(value)
result[extra.key] = value
return result
def _file__uid(
self,
path,
source__uid,
):
result = self.connection.execute(
select(
[file_records],
and_(
file_records.c.path==path,
file_records.c.source__uid==source__uid,
),
)
).first()
if result:
return result['uid']
def _file_path_exists(
self,
path,
source__uid,
):
return self.connection.execute(
select(
[file_records],
and_(
file_records.c.path==path,
file_records.c.source__uid==source__uid,
),
)
).first() and True or False
def _directory_metadata_exists(
self,
path,
#modified,
#accessed,
#owner,
#group,
#permission,
source__uid,
#link,
):
s = select(
[directory_records],
and_(
directory_records.c.source__uid==source__uid,
directory_records.c.path==path,
#directory_records.c.modified==modified,
#directory_records.c.owner==owner,
#directory_records.c.group==group,
#directory_records.c.permission==permission,
#directory_records.c.link==link,
),
).limit(1)
res = [f for f in self.connection.execute(s)]
if not res:
return None
return res
def _file_metadata_exists(
self,
path,
#modified,
#accessed,
#owner,
#group,
#permission,
#size,
source__uid,
#link,
):
s = select(
[file_records],
and_(
file_records.c.source__uid==source__uid,
file_records.c.path==path,
#file_records.c.modified==modified,
#file_records.c.owner==owner,
#file_records.c.group==group,
#file_records.c.permission==permission,
#file_records.c.size==size,
#file_records.c.link==link,
),
).limit(1)
res = [f for f in self.connection.execute(s)]
if not res:
return None
return res
def file_list(self, source, directory=None):
"""\
Return a list of paths in this directory source
"""
source__uid = self.source_exists(source)
if not source__uid:
raise Exception('No such source %r'%source)
if directory is None:
res = self.connection.execute(
select(
[file_records],
file_records.c.source__uid==source__uid,
).order_by(file_records.c.path.desc())
)
return [x for x in res]
else:
# Get all files where the path starts with the directory path but doesn't include sub-directories
res = self.connection.execute(
select(
[file_records],
and_(
file_records.c.source__uid==source__uid,
file_records.c.path.like(directory+'/%'),
not_(file_records.c.path.like(directory+'/%/%'))
),
).order_by(file_records.c.path.desc())
)
return [x for x in res]
def directory_update(
self,
uid,
path,
modified,
accessed,
owner,
group,
permission,
source='default',
link=None,
):
# First delete the current file
self.connection.execute('DELETE from directory WHERE uid = ?;', uid)
# Then add the new ones
return self.directory_add(
path,
modified,
accessed,
owner,
group,
permission,
source,
link,
)
def directory_add(
self,
path,
modified,
accessed,
owner,
group,
permission,
source='default',
link=None,
):
source__uid = self.source_exists(source)
if source__uid is None:
source__uid = self.source_add(source)
if not isinstance(path, unicode):
raise Exception('Expected a unicode string for %r'%path)
directory__uid = self.connection.execute(
directory_records.insert().values(
uid=make_uid(),
source__uid = source__uid,
path=path,
modified=modified,
accessed=accessed,
owner=owner,
group=group,
permission=permission,
link=link,
)
).inserted_primary_key[0]
return directory__uid
def directory_list(self, source, path=None, depth_first=None):
"""\
Return a list of paths in this directory source
"""
if depth_first not in [True, None]:
raise Exception(
'Expected the depth_first parameter to be None (unordered) '
'or True, not %r'%(
depth_first,
)
)
source__uid = self.source_exists(source)
if not source__uid:
raise Exception('No such source %r'%source)
if depth_first is None:
res = self.connection.execute(
select(
[directory_records],
directory_records.c.source__uid==source__uid,
).order_by(directory_records.c.path.asc())
)
return [x for x in res]
else:
res = self.connection.execute(
#select(
# [
# directory_records,
# (func.length('path') - func.length(func.replace(path, '/', '')))
# ],
# directory_records.c.source__uid==source__uid,
#).order_by(
# (func.length('path') - func.length(func.replace(path, '/', ''))).desc(),
# directory_records.c.path.asc(),
#)
'''
SELECT * from directory
WHERE
source__uid=?
ORDER BY
length(path)-length(replace(path, '/', '')) DESC,
path
''',
(source__uid,),
)
result = []
for x in res:
p = AttributeDict(x)
p['accessed'] = to_date(x['accessed'])
p['modified'] = to_date(x['modified'])
result.append(p)
return result
def source_add(self, source, created=None):
if self.source_exists(source):
raise Exception('A source named %r already exists'%source)
if '/' in source and self.source_exists(source.replace('/', '_')):
raise Exception("When sources are restored, '/' characters are replaced with '_' characters. A source named %r already exists so you can't use this name"%source.replace('/', '_'))
d = dict(
uid=make_uid(),
name=source,
created=created or datetime.datetime.now(),
)
res = self.connection.execute(source_records.insert().values(d))
assert d['uid'] == res.inserted_primary_key[0], [d['uid'], res.inserted_primary_key[0]]
return res.inserted_primary_key[0]
def source_exists(self, source):
res = self.connection.execute(select([source_records], source_records.c.name==source)).first()
if res:
return res.uid
return None
def source_list(self):
return [row[0] for row in self.connection.execute(select([source_records.c.name]))]
def source(self, source):
res = self.connection.execute(select([source_records], source_records.c.name==source)).first()
if res:
return res
else:
raise Exception('No such source %r'%source)
class Batch(object):
def __init__(self, source, store, metadata):
self.store = store
self.source = source
self.metadata = metadata
def unique_files(self, source):
source__uid = self.metadata.source_exists(source)
if not source__uid:
raise Exception('No such source %r'%source)
return [x for x in self.metadata.connection.execute('''
SELECT uid, hash, path, size from file where hash in (
SELECT hash FROM file WHERE source__uid = ?
EXCEPT
SELECT hash from file where source__uid != ?
) order by path desc;
''',
(source__uid, source__uid),
)]
def source_remove(self, source, skip_files=False):
source__uid = self.metadata.source_exists(source)
if not source__uid:
raise Exception('No such source %r'%source)
# Get a list of hashes in this source that aren't in any other source
trans = self.metadata.connection.begin()
size = 0
try:
# Remove the physical files
if not skip_files:
unique_files = self.unique_files(source)
unique_hashes = []
for unique_file in unique_files:
if not unique_file.hash in unique_hashes:
size+=unique_file.size
unique_hashes.append(unique_file.hash)
counter = 0
for unique_hash in unique_hashes:
counter += 1
log.info('Removing object %s [%s/%s]', unique_hash, counter, len(unique_hashes))
self.store.remove(unique_hash)
# Now remove all the metadata
# Extras
self.metadata.connection.execute('DELETE from extra WHERE uid in (SELECT uid FROM file WHERE source__uid=?);', source__uid)
# Files
self.metadata.connection.execute(
file_records.delete(
file_records.c.source__uid==source__uid
)
)
# Directories
self.metadata.connection.execute(
directory_records.delete(
directory_records.c.source__uid==source__uid
)
)
# The source
self.metadata.connection.execute(
source_records.delete().where(
source_records.c.uid==source__uid,
)
)
trans.commit()
except:
trans.rollback()
raise
else:
if not skip_files:
return unique_files, size
return None, None
def source_add(
self,
base_path,
source,
exclude=None,
base=None,
extras_function=None,
update=False,
hardlink=False,
skip_failures=False,
# Shouldn't we revert directory times too as part of this?
skip_revert_times=False,
ignore_new_symlink_times=False,
):
"""\
``base`` can be used to determine which part of the path shouldn't be stored for this command.
"""
source__uid = self.metadata.source_exists(source)
if source__uid is None:
source__uid = self.metadata.source_add(source)
errors = []
num_files = 0
num_dirs = 0
num_binary_add = 0
num_binary_error = 0
num_file_metadata_add = 0
num_file_metadata_replace = 0
num_directory_metadata_add = 0
num_directory_metadata_replace = 0
metadata = self.source.metadata(base_path)
del metadata['size']
for root, dirs, files in os.walk(unicode(base_path)):
dirs.sort()
for directory in dirs:
num_dirs += 1
path = os.path.join(root, directory)
log.debug('Inspecting directory %r to add to source %r', relpath(path, base_path), source)
metadata = self.source.metadata(path)
del metadata['size']
add_directory_metadata = True
replace_directory_metadata = False
if update:
directory_records = self.metadata._directory_metadata_exists(
relpath(path, base_path),
source__uid=source__uid,
#**metadata
)
if directory_records:
# There are existing directories with this path
if len(directory_records) > 1:
raise Exception(
'Found two directory rows in the database with the same path for the same directory. %s'%(
[(directory.uid, directory.path) for directory in directory_records]
)
)
directory_record = directory_records[0]
# If the metadata exists, we don't need to add the metadata again
add_directory_metadata=False
# Unless
metadata_format = [
source__uid,
relpath(path, base_path),
metadata['modified'],
metadata['owner'],
metadata['group'],
metadata['permission'],
metadata['link'],
]
db_format = [directory_records[0][1]] + list(directory_records[0][2:3]) + [directory_records[0][3]] + list(directory_records[0][5:])
if metadata_format != db_format:
log.info(
'Updating the existing directory metadata for %r',
relpath(path, base_path)
)
replace_directory_metadata=True
add_directory_metadata=False
if add_directory_metadata:
log.info('Adding directory %r to source %r', relpath(path, base_path), source)
self.metadata.directory_add(
relpath(path, base_path),
source=source,
**metadata
)
num_directory_metadata_add += 1
elif replace_directory_metadata:
log.info('Replacing directory %r in source %r', relpath(path, base_path), source)
# @@@ This gets run a lot if you update from a restored source, because archiver does not set the directory modified time
self.metadata.directory_update(
uid=directory_records[0].uid,
path=relpath(path, base_path),
source=source,
**metadata
)
num_directory_metadata_replace += 1
else:
log.debug('Directory %s is already present, skipping', relpath(path, base_path))
files.sort()
for filename in files:
num_files += 1
path = os.path.join(root, filename)
log.debug('Inspecting file %r to add to %r', path, source)
metadata = self.source.metadata(path)
log.debug('Obtained metadata %r', metadata)
add_file = True
add_file_metadata = True
replace_file_metadata = False
hash_str = ''
extras = None
if update:
file_records = self.metadata._file_metadata_exists(
relpath(path, base_path),
source__uid=source__uid,
#**metadata
)
if file_records:
# There are existing files with this path
if len(file_records) > 1:
raise Exception(
'Found two file rows in the database with the same path for the same file. %s'%(
[(file.uid, file.path) for file in file_records]
)
)
file_record = file_records[0]
# If the metadata exists, we don't need to add the file or metadata again
add_file=False
add_file_metadata=False
# Unless
# 1. There is no hash (and it isn't a link) and we aren't skipping failures, in which case we replace the metadata
if not file_record.hash and not skip_failures and not file_record.link:
# XXX What about link dsts with errors? They'd have a missing hash too (how about hash '' vs None)
add_file=True
replace_file_metadata=True
add_file_metadata=False
hash_str = file_record.hash
# 2. the metadata has changed
metadata_format = [
source__uid,
relpath(path, base_path),
metadata['modified'],
metadata['owner'],
metadata['group'],
metadata['permission'],
metadata['size'],
metadata['link'],
]
db_format = [file_records[0][1]] + list(file_records[0][3:4]) + [file_records[0][4]] + list(file_records[0][6:])
# Don't compare the microseconds part of a modified time
db_format[2] = datetime.datetime(
db_format[2].year,
db_format[2].month,
db_format[2].day,
db_format[2].hour,
db_format[2].minute,
db_format[2].second,
)
metadata_format[2] = datetime.datetime(
metadata_format[2].year,
metadata_format[2].month,
metadata_format[2].day,
metadata_format[2].hour,
metadata_format[2].minute,
metadata_format[2].second,
)
if metadata_format != db_format:
if metadata['link'] and ignore_new_symlink_times and metadata_format[0:2]+metadata_format[3:] == db_format[0:2]+db_format[3:]:
log.warning('Ignoring the new metadata for the symlink %r', relpath(path, base_path))
else:
log.info(
'Updating the existing metadata for %r',
relpath(path, base_path)
)
replace_file_metadata=True
add_file_metadata=False
if (replace_file_metadata or add_file_metadata) and extras_function is not None:
extras = extras_function(
self,
path,
AttributeDict(
path=relpath(path, base_path),
hash_str=hash_str,
**metadata
)
)
if add_file:
if os.path.islink(path) and not os.path.exists(path):
# This is a symbolic link to a path that doesn't exist
# rather than raise an error, we want to add the metadata,
# but not the data. We treat this as a file, whether it points
# to a directory or not because we can't tell
log.error('The symlink path %r doesn\'t exist', path)
else:
try:
hash_str = self.store.add(
relpath(path, base_path),
base_path,
hardlink=hardlink,
skip_revert_times=skip_revert_times,
)
except Exception, e:
errors.append(path)
log.error('Error adding file %s', e)
log.debug('Now %s errors, %s file(s) succesfully copied'%(len(errors), num_files))
num_binary_error += 1
else:
log.info('Successfully added %s', path)
num_binary_add += 1
else:
log.debug('File binary for %s is already present, skipping', relpath(path, base_path))
if replace_file_metadata:
log.warning('Updating exising metadata for %r', relpath(path, base_path))
self.metadata.file_update(
uid=file_records[0].uid,
path=relpath(path, base_path),
hash_str=hash_str,
source=source,
extras=extras,
**metadata
)
num_file_metadata_replace += 1
if add_file_metadata:
self.metadata.file_add(
relpath(path, base_path),
hash_str=hash_str,
source=source,
extras=extras,
**metadata
)
num_file_metadata_add += 1
if not replace_file_metadata and not add_file_metadata:
log.debug('File metadata for %s is already present, skipping', relpath(path, base_path))
results = dict(
stats = (
num_files,
num_binary_add,
num_binary_error,
num_file_metadata_add,
num_file_metadata_replace,
num_dirs,
num_directory_metadata_add,
num_directory_metadata_replace,
),
errors = errors
)
return results
def restore(
self,
browse_path,
source,
dst=None,
hardlink=False,
update_file_metadata=False,
update_directory_metadata=False,
):
"""\
Our algorithm here is to get the list of directories in a depth-first list.
Then for each directory, get the files it contains
"""
exit_on_exceptions = True
directories_created = False
if dst is None:
dst = source
if not os.path.exists(browse_path):
os.mkdir(browse_path)
base = os.path.join(browse_path, dst.replace('/', '_'))
source_time = None
if not os.path.exists(base):
os.mkdir(base)
source_time = self.metadata.source(source).created
log.info('Getting directory list ...')
directory_records = self.metadata.directory_list(source)
log.info('Making directory structure ...')
for directory_record in directory_records:
path = os.path.join(base, directory_record.path)
if not os.path.lexists(path):
# @@@ We don't support exapnding directories to the real directories and files the way we do below for files.
if directory_record.link is not None:
log.info('Making link %r -> %r', path, directory_record.link)
os.symlink(directory_record.link, path)
else:
log.info('Making directory %r', path)
directories_created = True
os.mkdir(path)
log.info('Getting file list ...')
file_records = self.metadata.file_list(source)
log.info('Restoring files ...')
#log.info('Restoring %s file(s) in the %r directory', len(file_records), directory_record.path)
for file_record in file_records:
log.debug('Restoring %r', file_record.path)
path = os.path.join(base, file_record.path)
if not os.path.lexists(path):
if not file_record.hash:
if file_record.link:
# It must be a broken symlink to a file or directory
log.warning('Restoring broken symlink %r -> %r', file_record.path, file_record.link)
os.symlink(file_record.link, path)
# Can't apply metadata to symlinks apparantly!
continue
else:
# It could be from a file which couldn't be read from the source material
log.warning('No data for source file %r, writing an empty file', file_record.path)
fp = open(path, 'w')
fp.write('')
fp.close()
continue
if file_record.link is not None and self.metadata._file_path_exists(
# It is a symlink to a file we can link to in the store
os.path.join('/'.join(
file_record.path.split('/')[:-1]),
file_record.link
),
self.metadata.source_exists(source)
):
os.symlink(file_record.link, path)
log.debug('Created link %r -> %r. Applying metadata', file_record.path, file_record.link)
try:
apply_metadata(
path=path,
permission=file_record.permission,
owner=file_record.owner,
group=file_record.group,
accessed=file_record.accessed,
modified=file_record.modified,
)
except Exception, e:
if exit_on_exceptions:
raise
log.error('Could not apply metadata to file %r; %r', file_record.path, e)
else:
src = os.path.join(self.store.store_path, file_record.hash[:4], file_record.hash)
if hardlink:
log.debug('Linking %r to %r', src, path)
os.link(src, path)
else:
log.debug('Copying %r to %r', src, path)
shutil.copy(
src,
path,
)
# Now try to apply the metadata
log.debug('Applying metadata to %r', file_record.path)
try:
apply_metadata(
path=path,
permission=file_record.permission,
owner=file_record.owner,
group=file_record.group,
accessed=file_record.accessed,
modified=file_record.modified,
)
except Exception, e:
if exit_on_exceptions:
raise
log.error('Could not apply metadata to file %r; %r', file_record.path, e)
elif os.path.exists(path) and not os.path.islink(path) and update_file_metadata:
st = os.lstat(path)
if file_record.permission != st.st_mode \
or file_record.owner != st.st_uid \
or file_record.group != st.st_gid \
or time.mktime(file_record.accessed.timetuple()) != st.st_atime \
or time.mktime(file_record.modified.timetuple()) != st.st_mtime:
# Find out if the file is a hardlink (should do this by looking at the inode of the archived file actually)
if st.st_nlink > 1:
log.error('Cannot reapply metadata to %r as it is a hardlink', path)
else:
log.info('Applying metadata to existing file %r', file_record.path)
try:
apply_metadata(
path=path,
permission=file_record.permission,
owner=file_record.owner,
group=file_record.group,
accessed=file_record.accessed,
modified=file_record.modified,
)
except Exception, e:
if exit_on_exceptions:
raise
log.error('Could not apply metadata to file %r; %r', file_record.path, e)
else:
log.debug('Metadata for %r is already up to date', file_record.path)
else:
if os.path.islink(path):
log.debug('Existing symlink restored %r -> %r', file_record.path, os.readlink(unicode(path)))
else:
log.debug('Existing file %r skipped', file_record.path)
if (directories_created and not hardlink) or update_directory_metadata:
log.info('Getting depth-first directory list ...')
directory_records = self.metadata.directory_list(source, depth_first=True)
log.info('Applying directory metadata ...')
for directory_record in directory_records:
try:
log.debug('Applying metadata to %r', directory_record.path)
apply_metadata(
path=os.path.join(base, directory_record.path),
permission=directory_record.permission,
owner=directory_record.owner,
group=directory_record.group,
accessed=directory_record.accessed,
modified=directory_record.modified,
)
except Exception, e:
if exit_on_exceptions:
raise
log.error('Could not apply metadata to directory %r; %r', directory_record.path, e)
if source_time:
set_time(base, source_time, source_time)
def extras_update(
self,
source,
extras_function,
path,
):
source__uid = self.metadata.source_exists(source)
if source__uid is None:
source__uid = self.metadata.source_add(source)
for file_record in self.metadata.file_list(source):
log.debug('Updating extras for file %r', file_record.path)
self.metadata.update_extras(
file_record.uid,
extras_function(
self,
os.path.join(path, file_record.path),
file_record,
)
)
|
Archiver
|
/Archiver-0.2.2.tar.gz/Archiver-0.2.2/archiver/api.py
|
api.py
|
import logging
import sys, os
import structlog
from copy import copy
import re
def copy_config(config):
'''Copy relevant information from one config to another.'''
new_config = {}
new_logging = config['logging'].copy()
new_structlog = {k:copy(v) for k,v in config['structlog'].items()}
new_config.update(logging=new_logging, structlog=new_structlog)
return new_config
# Regex to Match down or mixed-case usage of standard logging levels
canonical_levels = ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET',)
level_re = re.compile(
r"|".join((r'^{}$'.format(level) for level in canonical_levels)),
re.I
)
handler = None
already_configured = False
def setup_logging(config=None, level=None, stream=None, filename=None, filemode=None):
'''sets up both logging and structlog.'''
global handler, already_configured
asnake_root_logger = logging.getLogger('asnake')
if handler:
asnake_root_logger.removeHandler(handler)
if stream and filename:
raise RuntimeError("stream and filename are mutually exclusive and cannot be combined, pick one or the other")
from_env = os.environ.get('ASNAKE_LOG_CONFIG', None)
default = configurations.get(from_env, DEFAULT_CONFIG)
if not config:
config = copy_config(default)
if filename:
del config['logging']['stream']
level = level or config.get('level', None) or logging.INFO
if isinstance(level, str) and level_re.match(level):
level = getattr(logging, level.upper())
# Forward what's needed to put the log places
if stream:
config['logging']['stream'] = stream
if filemode:
config['logging']['filemode'] = filemode
if filename:
config['logging']['filename'] = filename
if 'filename' in config['logging']:
handler = logging.FileHandler(config['logging']['filename'],
mode=config['logging'].get('filemode', 'a'))
if 'stream' in config['logging']:
handler = logging.StreamHandler(config['logging']['stream'])
asnake_root_logger.addHandler(handler)
asnake_root_logger.setLevel(level)
structlog.reset_defaults()
structlog.configure(**config['structlog'])
already_configured = True
def get_logger(name=None):
if not already_configured:
setup_logging()
# Make sure it's under the root logger
if name and not name.startswith('asnake.'):
name = 'asnake.' + name
return structlog.get_logger(name)
# Log format is standard across all provided defaults
# This amounts to a log of serialized JSON events with UTC timestamps and various
# useful information attached, which formats exceptions passed to logging methods in exc_info
def default_structlog_conf(**overrides):
'''Generate a default configuration for structlog'''
conf = {
"logger_factory": structlog.stdlib.LoggerFactory(),
"wrapper_class":structlog.stdlib.BoundLogger,
"cache_logger_on_first_use": True,
"processors": [
structlog.stdlib.add_logger_name,
structlog.stdlib.add_log_level,
structlog.stdlib.PositionalArgumentsFormatter(),
structlog.processors.StackInfoRenderer(),
structlog.processors.format_exc_info,
structlog.processors.UnicodeDecoder(),
structlog.processors.TimeStamper(fmt='iso', utc=True),
structlog.processors.JSONRenderer()]
}
conf.update(**overrides)
return conf
def default_logging_conf(**overrides):
'''Generate a default stdlib logging configuration.'''
conf = {"level": logging.INFO, "format": "%(message)s"}
conf.update(**overrides)
return conf
# Provided example configurations for structlog.
configurations = {}
configurations['INFO_TO_STDERR'] = {
"logging": default_logging_conf(stream=sys.stderr),
"structlog": default_structlog_conf()
}
configurations['INFO_TO_STDOUT'] = {
"logging": default_logging_conf(stream=sys.stdout),
"structlog": default_structlog_conf()
}
configurations['INFO_TO_FILE'] = {
"logging": default_logging_conf(level=logging.INFO,
filename=os.path.expanduser("~/archivessnake.log"),
filemode="a"),
"structlog": default_structlog_conf(),
'level': 'INFO',
}
configurations['DEBUG_TO_STDERR'] = {
"logging": default_logging_conf(level=logging.DEBUG, stream=sys.stderr),
"structlog": default_structlog_conf(),
"level": "DEBUG"
}
configurations['DEBUG_TO_STDOUT'] = {
"logging": default_logging_conf(level=logging.DEBUG, stream=sys.stdout),
"structlog": default_structlog_conf(),
"level": "DEBUG"
}
configurations['DEBUG_TO_FILE'] = {
"logging": default_logging_conf(level=logging.DEBUG,
filename=os.path.expanduser("~/archivessnake.log"),
filemode="a"),
"structlog": default_structlog_conf(),
'level': 'DEBUG',
}
configurations['DEFAULT_CONFIG'] = configurations['INFO_TO_STDERR']
# Expose these as constants for user convenience
globals().update(**configurations)
|
ArchivesSnake
|
/ArchivesSnake-0.9.1-py3-none-any.whl/asnake/logging/__init__.py
|
__init__.py
|
from itertools import chain
from more_itertools import flatten
from copy import deepcopy
from collections.abc import Sequence
import json
import re
from asnake.logging import get_logger
component_signifiers = frozenset({"archival_object", "archival_objects"})
jmtype_signifiers = frozenset({"ref", "jsonmodel_type"})
searchdoc_signifiers = frozenset({"primary_type", "types", "id", "json"})
node_signifiers = frozenset({"node_type", "resource_uri"})
node_data_signifiers = frozenset({"child_count", "waypoints", "waypoint_size"})
solr_route_regexes = [
re.compile(r'/?repositories/\d+/top_containers/search/?')
]
def dispatch_type(obj):
'''Determines if object is JSON suitable for wrapping with a JSONModelObject, or a narrower subtype.
Returns either the correct class or False if no class is suitable.
Note: IN GENERAL, it is safe to use this to test if a thing is a JSONModel subtype, but you should
STRONGLY prefer :func:`wrap_json_object` for constructing objects, because some objects are wrapped,
and would need to be manually unwrapped otherwise. So, usage like this:
.. code-block:: python
jmtype = dispatch_type(obj, self.client)
if jmtype:
return wrap_json_object(obj, self.client)
is fine and expected, but the following is dangerous:
.. code-block:: python
jmtype = dispatch_type(obj, self.client)
if jmtype:
return jmtype(obj, self.client)
because it will break on wrapped or otherwise odd objects.'''
value = False
if isinstance(obj, dict):
# Handle wrapped objects returned by searches
if searchdoc_signifiers.issubset(set(obj)):
obj = json.loads(obj['json'])
ref_type = [x for x in obj['ref'].split("/") if not x.isdigit()][-1] if 'ref' in obj else None
if obj.get("jsonmodel_type", ref_type) in component_signifiers:
if node_data_signifiers.issubset(set(obj)):
return TreeNodeData
else:
value = ComponentObject
elif node_signifiers.intersection(obj.keys()) or ref_type == "tree":
value = TreeNode
elif jmtype_signifiers.intersection(obj.keys()):
value = JSONModelObject
return value
def wrap_json_object(obj, client=None):
'''Classify object, and either wrap it in the correct JSONModel type or return it as is.
Prefer this STRONGLY to directly using the output of :func:`dispatch_type`'''
if isinstance(obj, dict):
# Handle wrapped objects returned by searches
if searchdoc_signifiers.issubset(set(obj)):
obj = json.loads(obj['json'])
jmtype = dispatch_type(obj)
if jmtype:
obj = jmtype(obj, client)
return obj
def find_subtree(tree, uri):
'''Navigates a tree object to get a list of children of a specified archival object uri.'''
subtree = None
for child in tree['children']:
if child["record_uri"] == uri:
subtree = child
break # subtree found, all done!
else:
if not child['has_children']:
continue # this is a leaf, do not recurse
subtree = find_subtree(child, uri) # recurse!
if subtree: break
return subtree
# Base metaclass for shared functionality
class JSONModel(type):
'''Mixin providing functionality shared by JSONModel and JSONModelRelation classes.'''
def __init__(cls, name, parents, dct):
cls.__default_client = None
def default_client(cls):
'''return existing ASnakeClient or create, store, and return a new ASnakeClient'''
if not cls.__default_client:
from asnake.client import ASnakeClient
cls.__default_client = ASnakeClient()
return cls.__default_client
# Classes dealing with JSONModel imports
class JSONModelObject(metaclass=JSONModel):
'''A wrapper over the JSONModel representation of a single object in ArchivesSpace.'''
def __init__(self, json_rep, client = None):
self._json = json_rep
self._client = client or type(self).default_client()
self.is_ref = 'ref' in json_rep
def reify(self):
'''Convert object from a ref into a realized object.'''
if self.is_ref:
if '_resolved' in self._json:
self._json = self._json['_resolved']
else:
self._json = self._client.get(self._json['ref']).json()
self.is_ref = False
return self
@property
def id(self):
'''Return the id for the object if it has a useful ID, or else None.
Note: unlike uri, an id is Not fully unique within some collections returnable
by API methods. For example, searches can return different types of objects, and
agents have unique ids per agent_type, not across all agents.'''
candidate = self._json.get('uri', self._json.get('ref', None))
if candidate:
val = candidate.split('/')[-1]
if val.isdigit(): return(int(val))
def __dir__(self):
self.reify()
return sorted(chain(self._json.keys(),
(x for x in self.__dict__.keys() if not x.startswith("_{}__".format(type(self).__name__)))))
def __repr__(self):
result = "#<{}".format(self._json['jsonmodel_type'] if not self.is_ref else "ref" )
if 'uri' in self._json:
result += ':' + self._json['uri']
elif self.is_ref:
result += ':' + self._json['ref']
elif 'resource_uri' in self._json:
result += ':' + self._json['resource_uri']
return result + '>'
def __getattr__(self, key):
'''Access to properties on the JSONModel object and objects from descendant API routes.
attr lookup for JSONModel object is provided from the following sources:
- objects, lists of objects, and native values present in the wrapped JSON
- API methods matching the object's URI + the attribute requested
If neither is present, the method raises an AttributeError.'''
if key not in self._json and self.is_ref:
if key == 'uri': return self._json['ref']
self.reify()
if not key.startswith('_') and not key == 'is_ref':
if (not key in self._json.keys()) and 'uri' in self._json:
uri = "/".join((self._json['uri'].rstrip("/"), key,))
# Existence of route isn't enough, need to discriminate by type
# example: .../resources/:id/ordered_records which ALSO ought to be maybe treated as plural?
# This works, at the cost of a "wasted" full call if not a JSONModelObject
resp = self._client.get(uri, params={"all_ids":True})
if resp.status_code == 404:
raise AttributeError("'{}' has no attribute or route named '{}'".format(repr(self), key))
else:
jmtype = dispatch_type(resp.json())
if (jmtype):
return wrap_json_object(resp.json(), client=self._client)
if any(r.match(uri) for r in solr_route_regexes):
return SolrRelation(uri, client=self._client)
return JSONModelRelation(uri, client=self._client)
if isinstance(self._json[key], list) and len(self._json[key]) > 0:
jmtype = dispatch_type(self._json[key][0])
if len(self._json[key]) == 0 or jmtype:
return [wrap_json_object(obj, self._client) for obj in self._json[key]]
else:
# bare lists of Not Jsonmodel Stuff, ding dang note contents and suchlike
return self._json[key]
elif dispatch_type(self._json[key]):
return wrap_json_object(self._json[key], self._client)
else:
return self._json[key]
else: return self.__getattribute__(key)
def __str__(self):
return json.dumps(self._json, indent=2)
def __bytes__(self):
return str(self).encode('utf8')
def json(self):
'''return safe-to-edit copy wrapped dict representing JSONModelObject contents.'''
self.reify()
return deepcopy(self._json)
class ComponentObject(JSONModelObject):
'''Specialized JSONModel subclass representing Archival Objects. Mostly exists to provide a way to get TreeNodes from AOs rather than having to start at the resource.'''
@property
def tree(self):
'''Returns a TreeNode object for children of archival objects'''
try:
tree_object = find_subtree(self.resource.tree.json(), self.uri)
except:
raise AttributeError("'{}' has no attribute '{}'".format(repr(self), "tree"))
return wrap_json_object(tree_object, self._client)
class TreeNode(JSONModelObject):
'''Specialized JSONModel subclass representing nodes in trees, as returned
from `/repositories/:repo_id/resources/:id/tree <https://archivesspace.github.io/archivesspace/api/#get-a-resource-tree>`_.'''
def __repr__(self):
result = "#<TreeNode:{}".format(self._json['node_type'])
if "resource_uri" in self._json:
result += ":" + self._json['resource_uri']
elif "identifier" in self._json:
result += ":" + self._json['identifier']
return result + ">"
@property
def record(self):
'''returns the full JSONModelObject for a node'''
resp = self._client.get(self.record_uri)
return wrap_json_object(resp.json(), self._client)
@property
def walk(self):
'''Serial walk of all objects in tree and children (depth-first traversal)'''
yield self.record
yield from flatten(child.walk for child in self.children)
def node(self, node_uri):
'''A sub-route existing on resources, which returns info on the node passed in.
Returned as an instance of :class:`TreeNodeData`.'''
self.reify()
if self._json['node_type'] != 'resource':
raise NotImplementedError('This route only exists on resources')
else:
resp = self._client.get("/".join((self._json['record_uri'], 'tree/node',)), params={"node_uri": node_uri})
return wrap_json_object(resp.json(), self._client)
class TreeNodeData(JSONModelObject):
'''Object representing data about a node in a tree.'''
def __repr__(self):
return "#<TreeNodeData:{}:{}>".format(self._json['jsonmodel_type'], self._json['uri'])
def __getattr__(self, key):
if key not in self._json:
raise AttributeError("Property not present in tree data - it may exist on the record instead")
else:
return self._json[key]
@property
def record(self):
resp = self._client.get(self.uri)
return wrap_json_object(resp.json(), self._client)
class JSONModelRelation(metaclass=JSONModel):
'''A wrapper over index routes and other routes that represent groups of items in ASpace.
It provides two means of accessing objects in these collections:
- you can iterate over the relation to get all objects
- you can call the relation as a function with an id to get an object with a known id
e.g.
.. code-block:: python
for repo in ASpace().repositories:
# do stuff with repo here
ASpace.repositories(12) # object at uri /repositories/12
This object wraps the route and parameters, and does no caching - each iteration through a relation fetches data from ASpace fresh.
Additionally, JSONModelRelations implement `__getattr__`, in order to handle nested and subsidiary routes, such as the routes for individual types of agents.'''
def __init__(self, uri, params = {}, client = None):
self.uri = uri
self.client = client or type(self).default_client()
self.params = params
def __repr__(self):
return "#<JSONModelRelation:{}:{}>".format(self.uri, self.params)
def __iter__(self):
for jm in self.client.get_paged(self.uri, params=self.params):
yield wrap_json_object(jm, self.client)
def __call__(self, myid=None, **params):
'''Fetch a JSONModelObject from the relation by id.'''
# Special handling for resolve because it takes a string or an array and requires [] for array
if 'resolve' in params:
params['resolve[]'] = params['resolve']
del params['resolve']
if myid:
resp = self.client.get("/".join((self.uri.rstrip("/"), str(myid),)), params=params)
jmtype = dispatch_type(resp.json())
if (jmtype):
return wrap_json_object(resp.json(), client=self.client)
return resp.json()
else:
return self.with_params(**params)
def with_params(self, **params):
'''Return JSONModelRelation with same uri and client, but add kwargs to params.
Usage:
.. code-block:: python
for thing in ASpace().repositories(2).search.with_params(q="primary_type:resource"):
# do something with the things
'''
merged = {}
merged.update(self.params, **params)
return type(self)(self.uri, merged, self.client)
def __getattr__(self, key):
full_uri = "/".join((self.uri, key,))
if any(r.match(full_uri) for r in solr_route_regexes):
return SolrRelation(full_uri, params=self.params, client=self.client)
return type(self)(full_uri, params=self.params, client=self.client)
class ResourceRelation(JSONModelRelation):
'''subtype of JSONModelRelation for returning all resources from every repository
Usage:
.. code-block:: python
ASpace().resources # all resources from every repository
ASpace().resources(42) # resource with id=42, regardless of what repo it's in
'''
def __init__(self, params={}, client = None):
super().__init__(None, params, client)
def __iter__(self):
repo_uris = [r['uri'] for r in self.client.get('repositories').json()]
for resource in chain(*[self.client.get_paged('{}/resources'.format(uri), params=self.params) for uri in repo_uris]):
yield wrap_json_object(resource, self.client)
def __call__(self, myid=None, **params):
if 'resolve' in params:
params['resolve[]'] = params['resolve']
del params['resolve']
if myid:
repo_uris = [r['uri'] for r in self.client.get('repositories').json()]
for uri in repo_uris:
if myid in self.client.get(uri + '/resources', params={'all_ids': True}).json():
resp = self.client.get(uri + '/resources/{}'.format(myid), params=params)
jmtype = dispatch_type(resp.json())
if (jmtype):
return wrap_json_object(resp.json(), client=self.client)
return resp.json()
return {'error': 'Resource not found'}
else:
return self.with_params(**params)
def with_params(self, **params):
merged = {}
merged.update(self.params, **params)
return type(self)(self.params, self.client)
class ASNakeBadAgentType(Exception): pass
agent_types = ("corporate_entities", "people", "families", "software",)
agent_types_set = frozenset(agent_types)
class AgentRelation(JSONModelRelation):
'''subtype of JSONModelRelation for handling the `/agents` route hierarchy.
Usage:
.. code-block:: python
ASpace().agents # all agents of all types
ASpace().agents.corporate_entities # JSONModelRelation of corporate entities
ASpace().agents["corporate_entities"] # see above
ASpace().agents["people", "families"] # Multiple types of agents
'''
def __iter__(self):
for agent_type in agent_types:
yield from JSONModelRelation("/".join((self.uri.rstrip("/"), agent_type,)),
{"all_ids": True},
self.client)
def __getitem__(self, only):
'''filter the AgentRelation to only the type or types passed in'''
if isinstance(only, str):
if not only in agent_types_set:
raise ASnakeBadAgentType("'{}' is not a type of agent ASnake knows about".format(only))
return JSONModelRelation("/".join((self.uri.rstrip("/"), only,)),
{"all_ids": True},
self.client)
elif isinstance(only, Sequence) and set(only) < agent_types_set:
return chain(*(JSONModelRelation("/".join((self.uri.rstrip("/"), agent_type,)),
{"all_ids": True},
self.client) for agent_type in only))
else:
raise ASnakeBadAgentType("'{}' is not a type resolvable to an agent type or set of agent types".format(only))
def __repr__(self):
return "#<AgentRelation:/agents>"
def __call__(self, *args, **kwargs):
raise NotImplementedError("__call__ is not implemented on AgentRelation")
# override parent __getattr__ because needs to return base class impl for descendant urls
def __getattr__(self, key):
return type(self).__bases__[0]("/".join((self.uri, key,)), params=self.params, client=self.client)
def parse_jsondoc(doc, client):
return wrap_json_object(json.loads(doc['json']), client)
class SolrRelation(JSONModelRelation):
'''Sometimes, the API returns solr responses, so we have to handle that. Facets are still tbd, but should be doable, but also I'm not sure if they're widely used and thus need to be handled?.'''
def __iter__(self):
res = self.client.get(self.uri, params=self.params).json()
for doc in res['response']['docs']:
yield parse_jsondoc(doc, self.client)
def __call__(self, *args, **kwargs):
raise NotImplementedError("__call__ is not implemented for SolrRelations")
class UserRelation(JSONModelRelation):
'''"Custom" relation to deal with the API's failure to properly populate permissions for the `/users` index route'''
def __iter__(self):
for user in self.client.get_paged('/users', params=self.params):
yield wrap_json_object(self.client.get(user['uri']).json(), self.client)
@property
def current_user(self):
'''`/users/current-user` route.'''
return wrap_json_object(self.client.get('users/current-user', params=self.params).json(), self.client)
# override parent __getattr__ because needs to return base class impl for descendant urls
def __getattr__(self, key):
p = {k:v for k, v in self.params.items()}
if len(p) == 0:
p['all_ids'] = True
return type(self).__bases__[0]("/".join((self.uri, key,)), params=p, client=self.client)
class _JMeta(type):
def __getattr__(self, key):
def jsonmodel_wrapper(**kwargs):
out = {"jsonmodel_type": key}
out.update(**kwargs)
return out
if key.startswith('_'):
return super().__getattr__(self, key)
else:
return jsonmodel_wrapper
class JM(metaclass=_JMeta):
'''Helper class for creating hashes suitable for POSTing to ArchivesSpace.
Usage:
.. code-block:: python
JM.resource(title="A Resource's Title", ...) == {"jsonmodel_type": "resource", "title": "A Resource's Title", ...}
JM.agent_software(name="ArchivesSnake") == {"jsonmodel_type": "agent_software", "name": "ArchivesSnake"}
'''
pass # all functionality is provided by _JMeta
|
ArchivesSnake
|
/ArchivesSnake-0.9.1-py3-none-any.whl/asnake/jsonmodel/__init__.py
|
__init__.py
|
from requests import Session
from urllib.parse import quote
from numbers import Number
from collections.abc import Sequence, Mapping
import json
import asnake.configurator as conf
import asnake.logging as logging
log = None # initialized on first client init
class ASnakeAuthError(Exception): pass
class ASnakeWeirdReturnError(Exception): pass
def listlike_seq(seq):
'''Determine if a thing is a list-like (sequence of values) sequence that's not string-like.'''
return isinstance(seq, Sequence) and not isinstance(seq, (str, bytes, Mapping,))
def http_meth_factory(meth):
'''Utility method for producing HTTP proxy methods for ASnakeProxyMethods mixin class.
Urls are prefixed with the value of baseurl from the client's ASnakeConfig. Arguments are
passed unaltered to the matching requests.Session method.'''
def http_method(self, url, *args, **kwargs):
# aspace uses the PHP convention where array-typed form values use names with '[]' appended
if 'params' in kwargs:
kwargs['params'] = {k + '[]' if listlike_seq(v) and k[-2:] != '[]' else k:v for k,v in kwargs['params'].items()}
full_url = "/".join([self.config['baseurl'].rstrip("/"), url.lstrip("/")])
result = getattr(self.session, meth)(full_url, *args, **kwargs)
if result.status_code == 403 and self.config['retry_with_auth']:
self.authorize()
result = getattr(self.session, meth)(full_url, *args, **kwargs)
log.debug("proxied http method", method=meth.upper(), url=full_url, status=result.status_code)
return result
return http_method
class ASnakeProxyMethods(type):
'''Metaclass to set up proxy methods for all requests-supported HTTP methods'''
def __init__(cls, name, parents, dct):
for meth in ('get', 'post', 'head', 'put', 'delete', 'options',):
fn = http_meth_factory(meth)
fn.__name__ = meth
fn.__doc__ = '''Proxied :meth:`requests.Session.{}` method from :class:`requests.Session`'''.format(meth)
setattr(cls, meth, fn)
class ASnakeClient(metaclass=ASnakeProxyMethods):
'''ArchivesSnake Web Client'''
def __init__(self, **config):
global log
if 'config_file' in config:
self.config = conf.ASnakeConfig(config['config_file'])
else:
self.config = conf.ASnakeConfig()
self.config.update(config)
# Only a subset of logging config can be supported in config
# For more complex setups (configuring output format, say),
# configure logs in Python code prior to loading
#
# Properties supported are:
# filename, filemode, level, and default_config
# Default config can be any of the default configurations exposed in logging
if not log:
if not logging.already_configured and 'logging_config' in self.config:
if 'default_config' in self.config['logging_config']:
default_logging_config = logging.configurations.get(
self.config['logging_config']['default_config'])
del self.config['logging_config']['default_config']
else:
default_logging_config = None
logging.setup_logging(config = default_logging_config,
**self.config['logging_config'])
log = logging.get_logger(__name__)
if not hasattr(self, 'session'): self.session = Session()
self.session.headers.update({'Accept': 'application/json',
'User-Agent': 'ArchivesSnake/0.1'})
log.debug("client created")
def authorize(self, username=None, password=None):
'''Authorizes the client against the configured archivesspace instance.
Parses the JSON response, and stores the returned session token in the session.headers for future requests.
Asks for a "non-expiring" session, which isn't truly immortal, just long-lived.'''
username = username or self.config['username']
password = password or self.config['password']
log.debug("authorizing against ArchivesSpace", user=username)
resp = self.session.post(
"/".join([self.config['baseurl'].rstrip("/"), 'users/{username}/login']).format(username=quote(username)),
data={"password": password, "expiring": False}
)
if resp.status_code != 200:
log.debug("authorization failure", status=resp.status_code)
raise ASnakeAuthError("Failed to authorize ASnake with status: {}".format(resp.status_code))
else:
session_token = json.loads(resp.text)['session']
self.session.headers['X-ArchivesSpace-Session'] = session_token
log.debug("authorization success", session_token=session_token)
return session_token
def get_paged(self, url, *args, page_size=100, **kwargs):
'''get list of json objects from urls of paged items'''
params = {}
if "params" in kwargs:
params.update(**kwargs['params'])
del kwargs['params']
# special-cased bc all_ids doesn't work on repositories index route
if "all_ids" in params and url in {"/repositories", "repositories"}:
del params['all_ids']
params.update(page_size=page_size, page=1)
current_page = self.get(url, params=params, **kwargs)
current_json = current_page.json()
# Regular paged object
if hasattr(current_json, 'keys') and \
{'results', 'this_page', 'last_page'} <= set(current_json.keys()):
while current_json['this_page'] <= current_json['last_page']:
for obj in current_json['results']:
yield obj
if current_json['this_page'] == current_json['last_page']: break
params['page'] += 1
current_page = self.get(url, params=params)
current_json = current_page.json()
# routes that just return a list, or ids, i.e. queries with all_ids param
elif isinstance(current_json, list):
# e.g. repositories
if len(current_json) >= 1:
if hasattr(current_json[0], 'keys'):
for obj in current_json:
yield obj
elif isinstance(current_json[0], Number):
for i in current_json:
yield self.get("/".join([url, str(i)])).json()
else:
raise ASnakeWeirdReturnError("get_paged doesn't know how to handle {}".format(current_json))
else:
raise ASnakeWeirdReturnError("get_paged doesn't know how to handle {}".format(current_json))
|
ArchivesSnake
|
/ArchivesSnake-0.9.1-py3-none-any.whl/asnake/client/web_client.py
|
web_client.py
|
from datetime import date
import re
from rapidfuzz import fuzz
from asnake.jsonmodel import JSONModelObject
from string import Formatter
from collections.abc import Mapping
from itertools import chain
def resolve_to_uri(thingit):
"""Given any of:
- the URI for an ArchivesSpace object
- a dict with a key 'uri' or 'ref' containing said URI
- an object responding to .json() returning such a dict
this method will return a string containing the URI for that resource.
"""
uri = None
# if object has .json(), replace with value of .json()
if callable(getattr(thingit, 'json', None)):
thingit = thingit.json()
if isinstance(thingit, str):
uri = thingit
elif isinstance(thingit, Mapping):
uri = thingit.get("uri", thingit.get("ref", None))
if not uri:
raise Exception('Could not resolve "{}" to a URI'.format(thingit))
return uri
def resolve_to_json(thingit, client):
"""Given any of:
- the URI for an ArchivesSpace object
- an object responding to .json() returning such a dict
this method will return a JSON representation of that object.
"""
json = None
if isinstance(thingit, dict):
json = thingit
elif callable(getattr(thingit, 'json', None)):
json = thingit.json()
else:
uri = resolve_to_uri(thingit)
json = client.get(thingit).json()
if not json:
raise Exception('Could not resolve {} to JSON.'.format(thingit))
return json
def get_note_text(note, client):
"""Parses note content from different note types.
:param dict: an ArchivesSpace note.
:returns: a list containing note content.
:rtype: list
"""
def parse_subnote(subnote, client):
"""Parses note content from subnotes.
:param dict: an ArchivesSpace subnote.
:returns: a list containing subnote content.
:rtype: list
"""
subnote = resolve_to_json(subnote, client)
if subnote["jsonmodel_type"] in [
"note_orderedlist", "note_index"]:
content = subnote["items"]
elif subnote["jsonmodel_type"] in ["note_chronology", "note_definedlist"]:
content = []
for k in subnote["items"]:
for i in k:
content += k.get(i) if isinstance(k.get(i),
list) else [k.get(i)]
else:
content = subnote["content"] if isinstance(
subnote["content"], list) else [subnote["content"]]
return content
note = resolve_to_json(note, client)
if note["jsonmodel_type"] in ["note_singlepart", "note_langmaterial"]:
content = note["content"]
elif note["jsonmodel_type"] == "note_bibliography":
data = []
data += note["content"]
data += note["items"]
content = data
elif note["jsonmodel_type"] == "note_index":
data = []
for item in note["items"]:
data.append(item["value"])
content = data
else:
subnote_content_list = [parse_subnote(sn, client) for sn in note["subnotes"]]
content = [
c for subnote_content in subnote_content_list for c in subnote_content]
return content
def text_in_note(note, query_string, client, confidence=97):
"""Performs fuzzy searching against note text.
:param dict note: an ArchivesSpace note.
:param str query_string: a string to match against.
:param int confidence: minimum confidence ratio to match against.
:returns: True if a match is found for `query_string`, False if no match is
found.
:rtype: bool
"""
note = resolve_to_json(note, client)
note_content = get_note_text(note, client)
ratio = fuzz.partial_ratio(
" ".join([n.lower() for n in note_content]),
query_string.lower(),
score_cutoff=confidence)
return bool(ratio)
def format_from_obj(obj, format_string, client):
"""Generates a human-readable string from an object.
:param JSONModelObject or dict: an ArchivesSpace object.
:returns: a string in the chosen format.
:rtype: str
"""
obj = resolve_to_json(obj, client)
if not format_string:
raise Exception("No format string provided.")
else:
try:
d = {}
matches = [i[1] for i in Formatter().parse(format_string) if i[1]]
for m in matches:
d.update({m: obj[m]})
return format_string.format(**d)
except KeyError as e:
raise KeyError(
"The field {} was not found in this object".format(str(e)))
def format_resource_id(resource, client, separator=":"):
"""Concatenates the four-part ID for a resource record.
:param dict resource: an ArchivesSpace resource.
:param str separator: a separator to insert between the id parts. Defaults
to `:`.
:returns: a concatenated four-part ID for the resource record.
:rtype: str
"""
resource = resolve_to_json(resource, client)
resource_id = []
for x in range(4):
try:
resource_id.append(resource["id_{0}".format(x)])
except KeyError:
break
return separator.join(resource_id)
def find_closest_value(archival_object, key, client):
"""Finds the closest value matching a key.
Starts with an archival object, and iterates up through its ancestors
until it finds a match for a key that is not empty or null.
:param JSONModelObject archival_object: the URI for an archival object, a
dict with a key 'uri' or 'ref' containing said URI, or an object
responding to .json() returning such a dict
:param str key: the key to match against.
:returns: The value of the key, which could be a str, list, or dict.
:rtype: str, list, or key
"""
ao_uri = resolve_to_uri(archival_object)
archival_object = client.get(ao_uri, params={'resolve': ['ancestors']}).json()
if archival_object.get(key) not in ["", [], {}, None]:
return archival_object[key]
else:
for ancestor in archival_object.get("ancestors"):
anc = ancestor.get("_resolved")
if anc.get(key) not in ["", [], {}, None]:
return anc[key]
def get_orphans(object_list, null_attribute, client):
"""Finds objects in a list which do not have a value in a specified field.
:param list object_list: a list of URIs for an archival object, dicts with
a key 'uri' or 'ref' containing said URI, or objects responding to
.json() returning such a dict
:param null_attribute: an attribute which must be empty or null.
:yields: a list of ArchivesSpace objects.
:yield type: dict
"""
for obj in object_list:
obj = resolve_to_json(obj, client)
if obj.get(null_attribute) in ["", [], {}, None]:
yield obj
def get_date_display(date, client):
"""Returns a date expression for a date object.
Concatenates start and end dates if no date expression exists.
:param dict date: an ArchivesSpace date
:returns: date expression for the date object.
:rtype: str
"""
date = resolve_to_json(date, client)
try:
expression = date["expression"]
except KeyError:
if date.get("end"):
expression = "{0}-{1}".format(date["begin"], date["end"])
else:
expression = date["begin"]
return expression
def indicates_restriction(rights_statement, restriction_acts, client):
"""Parses a rights statement to determine if it indicates a restriction.
:param dict rights_statement: an ArchivesSpace rights statement.
:returns: True if rights statement indicates a restriction, False if not.
:rtype: bool
"""
rights_statement = resolve_to_json(rights_statement, client)
if is_expired(rights_statement.get("end_date")):
return False
for act in rights_statement.get("acts"):
if (act.get("restriction")
in restriction_acts and not is_expired(act.get("end_date"))):
return True
return False
def is_expired(date_str):
"""Takes a date and then checks whether today's date is before or after passed date.
Will return a ValueError if passed date argument is an invalid date.
:param string date: an ISO-formatted representation of a date
:returns: False if date argument is after today or True if
:rtype: bool
"""
parsed_date = date.fromisoformat(date_str)
return parsed_date < date.today()
def is_restricted(archival_object, query_string, restriction_acts, client):
"""Parses an archival object to determine if it is restricted.
Iterates through notes, looking for a conditions governing access note
which contains a particular set of strings.
Also looks for associated rights statements which indicate object may be
restricted.
:param dict archival_object: an ArchivesSpace archival_object.
:param list restriction_acts: a list of strings to match restriction act against.
:returns: True if archival object is restricted, False if not.
:rtype: bool
"""
archival_object = resolve_to_json(archival_object, client)
for note in archival_object["notes"]:
if note["type"] == "accessrestrict":
if text_in_note(note, query_string.lower(), client):
return True
for rights_statement in archival_object["rights_statements"]:
if indicates_restriction(rights_statement, restriction_acts, client):
return True
return False
def strip_html_tags(string):
"""Strips HTML tags from a string.
:param str string: An input string from which to remove HTML tags.
"""
tag_match = re.compile("<.*?>")
cleantext = re.sub(tag_match, "", string)
return cleantext
def get_object_locations(ao_uri, client):
"""Given any of:
- the URI for an archival object
- a dict with a key 'uri' or 'ref' containing said URI
- an object responding to .json() returning such a dict
and an :class:`asnake.client.ASnakeClient`, this method will return a
generator which yields the JSON representation of any locations associated
with the archival object.
"""
ao_uri = resolve_to_uri(ao_uri)
resp = client.get(ao_uri, params={'resolve': ['top_container::container_locations']})
if resp.status_code != 200:
raise Exception("Unable to fetch archival object with resolved container locations")
for instance in resp.json()['instances']:
for container_loc in instance['sub_container']['top_container']['_resolved']['container_locations']:
yield container_loc['_resolved']
def walk_tree(thingit, client):
"""Given any of:
- the URI for a resource
- the URI for an archival object
- a Mapping containing such a URI under the key 'uri'
and an :class:`asnake.client.ASnakeClient`, this method will return a generator
which yields the JSON representation of each successive element in the resource's tree,
in order."""
uri = resolve_to_uri(thingit)
params = {'offset': 0}
if not 'archival_object' in uri:
resource_uri = uri
else:
node_uri = uri
params['node_uri']= node_uri
if isinstance(thingit, Mapping) and 'resource' in thingit:
resource_uri = thingit['resource']['ref']
else:
resource_uri = client.get(node_uri).json()['resource']['ref']
waypoints_uri = "/".join([resource_uri, "tree/waypoint"])
if 'node_uri' in params:
starting_waypoint = client.get("/".join([resource_uri, "tree/node"]), params=params).json()
else:
starting_waypoint = client.get("/".join([resource_uri, "tree/root"]), params=params).json()
yield from _handle_waypoint(waypoints_uri, starting_waypoint, client)
def _page_waypoint_children(waypoints_uri, waypoint, client):
params = {}
if not 'resources' in waypoint['uri']:
params['parent_node'] = waypoint['uri']
for i in range(waypoint['waypoints']):
params['offset'] = i
for wp in client.get(waypoints_uri, params=params).json():
yield wp
def _handle_waypoint(waypoints_uri, waypoint, client):
# yield the record itself
yield client.get(waypoint['uri']).json()
# resource, omit parent_node_param
for wp in _page_waypoint_children(waypoints_uri, waypoint, client):
yield from _handle_waypoint(waypoints_uri, wp, client)
|
ArchivesSnake
|
/ArchivesSnake-0.9.1-py3-none-any.whl/asnake/utils/__init__.py
|
__init__.py
|
from asnake.client import ASnakeClient
import asnake.jsonmodel as jm
from asnake.jsonmodel import *
from collections.abc import Sequence
from itertools import chain
from boltons.setutils import IndexedSet
import json
import re
class ASnakeBadReturnCode: pass
class ASpace():
# this happens when you call ASpace()
def __init__(self, **config):
# Connect to ASpace using .archivessnake.yml
self.client = ASnakeClient(**config)
self.client.authorize()
m = re.match(r'\(v?(.+\))', self.client.get('version').text)
if m:
self.version = m[1]
else:
self.version = 'unknown version'
def __getattr__(self, attr):
'''returns the JSONModelRelation representing the route with the same name as the attribute requested.'''
if not attr.startswith('_'):
return JSONModelRelation("/{}".format(attr), params={"all_ids": True}, client = self.client)
@property
def resources(self):
'''return all resources from every repo.'''
return ResourceRelation({}, self.client)
@property
def agents(self):
'''returns an AgentRelation.'''
return AgentRelation("/agents", {}, self.client)
@property
def users(self):
'''returns a UserRelation.'''
return UserRelation("/users", {}, self.client)
def by_external_id(self, external_id, record_types=None):
'''return any resources fetched from the 'by-external-id' route.
Note: while the route will return differently depending on how many records are returned,
this method deliberately flattens that out - it will _always_ return a generator, even if only
one record is found.'''
params = {"eid": external_id}
if record_types: params['type[]'] = record_types
res = self.client.get('by-external-id', params=params)
if res.status_code == 404:
return []
elif res.status_code == 300: # multiple returns, bare list of uris
yield from (wrap_json_object({"ref": uri}, self.client) for uri in IndexedSet(res.json()))
elif res.status_code == 200: # single obj, redirects to obj with 303->200
yield wrap_json_object(res.json(), self.client)
else:
raise ASnakeBadReturnCode("by-external-id call returned '{}'".format(res.status_code))
def from_uri(self, uri):
'''returns a JSONModelObject representing the URI passed in'''
return wrap_json_object(self.client.get(uri).json(), self.client)
|
ArchivesSnake
|
/ArchivesSnake-0.9.1-py3-none-any.whl/asnake/aspace/__init__.py
|
__init__.py
|
# Archy
This is a python package is created to facilitate calculations in the field of aerospace Mathematics Engineering in particular and mathematics geometry in general
As it can calculate the area of shapes and their perimeter with several types of input
[Archiy](https://pypi.org/project/Archiy/1.0.0/)
## shapes:
- **Point** : accept arguments : a , b represented the point coordinates in the orthogonal and homogeneous parameters
This class contain ` __init__`, `__repr__` and 'distance' methods, where the distance method take a point object as parameter to calculate the distance between the points.
Example :
```python
p1 = Point(1, 30)
p2 = Point(4, 80)
p1.distance(p2)
```
- **Square** : Square class have 2 types of declaration :
- init \* args:
height: height of the rectangle
width: width
- init \*\* kwargs:
points: a, b, c, d
This class contain ` __init__` and `__repr__` and other methods :
- perimetre() : this method calculate Square perimetre.
- surface() : this method calculate Square surface.
- diagonal() : this method calculate Square diagonal.
Example :
```python
from archy import Point, Square
p1 = Point(1, 30)
p2 = Point(4, 80)
p3 = Point(6, 20)
p4 = Point(8, 10)
### Square ###
S1 = Square(4)
S2 = Square(a=p1, b=p2, c=p3, d=p4)
print(f"Square Side > {S1} \n")
print(f"Square side Diagonal > {S1.diagonal()}\n")
print(f"Square side surface > {S1.surface()}\n")
print(f"Square side perimetre > {S1.perimetre()}\n")
```
- **Triangle** : Triangle class have 2 types of declaration :
- init \* args:
accept 3 params type(int) representing side1, side2, side3
example:
```python
T = Triangle(5, 2, 3)
```
<br/>
- init \*\* kwargs:
accept 3 params (a,b,c) type(Point) representing side1, side2, side3
example:
```python
from archiy import Point, Triangle
p1 = Point(1, 30)
p2 = Point(4, 80)
p3 = Point(6, 20)
T = Triangle(a=p1, b=p2, c=p3)
```
This class contain ` __init__` , `__repr__` and 'perimetre'.
The perimetre method allow to calculate the triangle perimeter :
```python
from archiy import Triangle
T = Triangle(1,2,10)
T1.perimetre()
```
- **Rectangle** : Rectangle class have 2 types of declaration :
- init \* args: accept 2 params : (height,width)
example:
```python
from archiy import
R = Rectangle(5,2)
```
- init \*\* kwargs: accept 4 params (a,b,c,d) type(Point)
example:
```python
from archiy import Point, Rectangle
p1 = Point(1, 30)
p2 = Point(4, 80)
p3 = Point(6, 20)
p4 = Point(8, 10)
### Rectangle ###
R = Rectangle(5, 5)
print(f"Rectangle > {R}")
print(f"Rectangle Surface > {R.surface()} \n")
```
|
Archiy
|
/Archiy-1.0.1.tar.gz/Archiy-1.0.1/README.md
|
README.md
|
from math import sqrt
class Point():
'''
Point class :
points arguments : a , b
'''
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "({} , {})".format(self.a, self.b)
def distance(self, other):
try:
if not isinstance(other, Point):
raise ValueError('the other must be point')
distance = sqrt(pow(self.a-other.a, 2) + pow(self.b - other.b, 2))
return distance
except ValueError as r:
print(r.__class__() + r)
class Rectangle():
'''
Rectangle class
have 2 types of declaration :
1 - init *args :
height : height of the rectangle
width: width
2 - init **kwargs :
points : a , b , c , d
'''
def __init__(self, *args, **kwargs):
try:
if len(args) > 0 and len(kwargs) > 0:
raise ValueError(
'the class can take one type of arguments args or kwargs')
if len(kwargs) > 0:
for key, value in kwargs.items():
if not isinstance(value, Point):
raise ValueError('all params must be points')
if len(kwargs) < 4:
raise KeyError('number of kwargs must be 4')
# if kwargs['a']
self.a = kwargs['a']
self.b = kwargs['b']
self.c = kwargs['c']
self.d = kwargs['d']
self.height = Point.distance(self.a, self.b)
self.width = Point.distance(self.b, self.c)
if len(args) > 0:
if len(args) < 2:
raise KeyError('number of args must be 2')
self.height = args[0]
self.width = args[1]
except ValueError as r:
print(r)
def __repr__(self):
try:
return 'a = {} , b = {} , c = {} , d = {} \n height : {} , width : {} '.format(self.a, self.b, self.c, self.d, self.height, self.width)
except:
return 'height : {} , width : {}'.format(self.height, self.width)
'''
surface this method calculate a surface of the object
'''
def surface(self):
surface = self.height * self.width
return surface
def perimetre(self):
perimetre = ((2*self.width)+(2*self.height))
return perimetre
def diagonal(self):
diagonal = sqrt(pow(self.height, 2)+pow(self.width, 2))
return diagonal
class Square():
'''
Square class
have 2 types of declaration:
1 - init * args:
height: height of the rectangle
width: width
2 - init ** kwargs:
points: a, b, c, d
'''
def __init__(self, *args, **kwargs):
try:
if len(args) > 0 and len(kwargs) > 0:
raise ValueError(
'the class can take one type of arguments args or kwargs')
if len(kwargs) > 0:
for key, value in kwargs.items():
if not isinstance(value, Point):
raise ValueError('all params must be points')
if len(kwargs) < 4:
raise KeyError('number of kwargs must be 4')
self.a = kwargs['a']
self.b = kwargs['b']
self.c = kwargs['c']
self.d = kwargs['d']
self.side = Point.distance(self.a, self.b)
if len(args) > 0:
if len(args) < 1:
raise KeyError('number of args must be 1')
self.side = args[0]
except ValueError as r:
print(r)
def __repr__(self):
try:
return 'a = {} , b = {} , c = {} , d = {} \n side = {} '.format(self.a, self.b, self.c, self.d, self.side)
except:
return 'side : {}'.format(self.side)
'''
surface methode to calculate square surface
'''
def surface(self):
surface = pow(self.side, 2)
return surface
'''
perimetre methode to calculate square perimetre
'''
def perimetre(self):
perimetre = self.side * 4
return perimetre
'''
methode to calculate square diagonal
'''
def diagonal(self):
diagonal = sqrt(pow(self.side, 2)+pow(self.side, 2))
return diagonal
class Triangle():
def __init__(self, *args, **kwargs):
if len(args) > 0 and len(kwargs) > 0:
raise ValueError('Triangle class accept one type of argument')
if len(args) > 0:
try:
if len(args) == 3:
self.side1 = args[0]
self.side2 = args[1]
self.side3 = args[2]
except ValueError as r:
print(r)
if len(kwargs) > 0:
if len(kwargs) == 3:
for key, value in kwargs.items():
if not isinstance(value, Point):
raise ValueError('all params must be points')
try:
self.a = kwargs["a"]
self.b = kwargs['b']
self.c = kwargs["c"]
self.side1 = Point.distance(self.a, self.b)
self.side2 = Point.distance(self.b, self.c)
self.side3 = Point.distance(self.c, self.a)
except ValueError as r:
print(r)
def __repr__(self):
try:
return 'a = {} , b = {} , c = {} \n side1 = {} , side2 = {} , side3 = {}'.format(self.a, self.b, self.c, self.side1, self.side2, self.side3)
except:
return 'side1 = {} , side2 = {} , side3 = {}'.format(self.side1, self.side2, self.side3)
def perimetre(self):
perimetre = self.side1+self.side2+self.side3
return perimetre
|
Archiy
|
/Archiy-1.0.1.tar.gz/Archiy-1.0.1/archy/shape.py
|
shape.py
|
ArconaiAudio
============
Allows you to listen to Arconai through your terminal
Installation
------------
.. code-block:: bash
pip3 install --user ArconaiAudio
Dependencies
------------
You need to install `mpv <https://mpv.io/installation/>`_ as well
Ubuntu
^^^^^^
.. code-block:: bash
sudo add-apt-repository ppa:mc3man/mpv-tests
sudo apt-get install mpv
OS X
^^^^
.. code-block:: bash
brew install mpv --with-bundle
Usage
-----
In your terminal, run
.. code-block:: bash
ArconaiAudio
and you will see a selection
.. image:: docs/images/Screenshot_2019-03-16_18-04-54.png
:target: docs/images/Screenshot_2019-03-16_18-04-54.png
:alt: selecting show type
After selection a show type, the relevant show names will be displayed. In the input menu, you can type in the show you want to listen to. Word completion is automatically enabled, so pressing ``TAB`` will help selection. Selection through ``UP`` or ``DOWN`` arrow keys also works.
.. image:: docs/images/Screenshot_2019-03-16_18-04-04.png
:target: docs/images/Screenshot_2019-03-16_18-04-04.png
:alt: selecting show name
**NOTE**\ : Show names are case sensitive
Options
^^^^^^^
.. code-block:: bash
ArconaiAudio [show type] [show name]
Show Type
~~~~~~~~~
* shows
* cable
* movies
Show Name
~~~~~~~~~
The name of the show under the specific **Show Type**. The name is case sensitive, and for names with spaces in the title, you should put quotes around it.
Example
^^^^^^^
Running
.. code-block:: bash
ArconaiAudio shows Scrubs
will play the **Scrubs** audio
.. code-block:: bash
ArconaiAudio shows "Always Sunny in Philadelphia"
will play the **Always Sunny in Philadelphia** audio
|
ArconaiAudio
|
/ArconaiAudio-1.1.2.tar.gz/ArconaiAudio-1.1.2/README.rst
|
README.rst
|
##############################################################################################################################################
##############################################################################################################################################
' IMPORT SECTION: '
##############################################################################################################################################
##############################################################################################################################################
def __cmd__(command):
try:
import os
os.system(command)
except Exception as e:
print("Something went wrong in accessing the command line. This feature was well tested on Windows OS.\n This part belongs to importing of modules if they are not installed in your computer yet.\nTry installing matplotlib and pyserial manually via pip.\nAutomatic installation fail due to unaccessable command line !\n")
print(e)
def __installationCheck__():
try:
import serial
Module_1=True
except Exception:
Module_1=False
print("pyserial module not found.\nDon't worry, we'll install it in your pc automatically.\nJust make sure you have good internet connection !!")
try:
import matplotlib
Module_2=True
except Exception:
Module_2=False
print("matplotlib module not found.\nDon't worry, we'll install it in your pc automatically.\nJust make sure you have good internet connection !!")
return(1 if (Module_1 and Module_2)==True else 0)
def __installModules__():
try:
__cmd__("pip install pyserial")
__cmd__("pip install matplotlib")
except Exception as e:
print(e)
def __modulesInitialization__():
n=1
while(__installationCheck__()!=1):
__installModules__()
if(n>3):
print("This module consists auto-pip package installation yet unable to download 'matplotlib' and 'pyserial'")
print("Try switching on your internet connection or download those two modules via pip manually")
raise ModuleNotFoundError
break
n+=1
return
__modulesInitialization__()
import time
from itertools import zip_longest as zip_longest
import serial
from serial import *
import matplotlib.pyplot as plt
from matplotlib import style
##############################################################################################################################################
##############################################################################################################################################
' Data Science FUNCTIONS : '
##############################################################################################################################################
##############################################################################################################################################
# Used to hybridize a given set of list
def hybridize(li1,li2=None):
if li2==None:
li2=li1.copy()
li1=[i for i in range(len(li2))]
return(li1,li2)
# Functionality of compress() enhanced to hybrids
def cpress(index,li=[]):
try:
#inittialization
if li==[] :
li=index.copy()
index= [j for j in range(len(li))]
retli=[li[0]]
ind=[0]
i=1
for i in range(len(li)):
lastEle = retli[-1]
currentEle = li[i]
if (currentEle!=lastEle):
retli.append(currentEle)
ind.append(index[i])
return(ind,retli)
except Exception as e:
print(str(e)+"\n ERROR ID - cpress")
# You know what I do
def __elements(g_string):
try:
gstring=str(g_string)
ng=len(gstring)-1
lg=list()
ig=0
while(ig<=ng):
lg.append(gstring[ig])
ig+=1
return(lg)
except Exception as e:
print(str(e)+'\n ERROR ID - elements')
# Checks if all the elements in the given list are unique
def __isunique(Data):
try:
nData=len(Data)
nSet =len(list(set(Data)))
if(nData==nSet):
return(True)
else:
return(False)
except Exception as e:
print(str(e)+'\nERROR ID - isunique')
# draws a line parallel to y axis
def horizontal(y,lbl='horizontal',start=0,end=10,stl='dark_background',color='yellow'):
try:
style.use(stl)
plt.plot([start,end],[y,y],label=lbl,linewidth=2,color=color)
except Exception as e:
print(str(e)+'\nERROR ID - yline')
# draws a line parallel to x axis.
def vertical(x,lbl='vertical',start=0,end=10,stl='dark_background',color='yellow'):
try:
style.use(stl)
plt.plot([x,x],[start,end],label=lbl,linewidth=2,color=color)
except Exception as e:
print(str(e)+'\nERROR ID - xline')
# Creates a marker:
def marker(x,y,limit=1,lbl="marker",color='yellow',stl='dark_background'):
style.use(stl)
vertical(x,lbl=lbl,start=y-limit,end=y+limit,color=color)
horizontal(y,lbl=lbl,start=x-limit,end=x+limit,color=color)
# Converts two lists into a dictionary
def __liDict(li1,li2):
try:
dictionary = dict(zip(li1,li2))
return(dictionary)
except Exception as e:
print(str(e)+'ERROR ID - lidict')
# Assigns a value to a string
def assignValue(str_list):
try:
key=list(set(str_list))
n=len(list(set(str_list)))//2
retLi=[]
if(len(list(set(str_list)))%2==0):
for i in range(-n+1,n+1):
retLi.append(i)
return(__liDict(key,retLi))
else:
for i in range(-n,n+1):
retLi.append(i)
return(__liDict(key,retLi))
except Exception as e:
print(str(e)+'ERROR ID - assignValue')
#finds the difference between two numbers
def __diff(x,y):
try:
return(abs(x-y))
except Exception as e:
print(str(e)+'ERROR ID - diff')
# Converts all the elements of the list to integers
def __numlist(Index,li):
try:
retIndex=[]
retlist=[]
for a in range(len(li)):
retlist.append(float(li[a]))
retIndex.append(Index[a])
return(retIndex,retlist)
except Exception as e:
print(str(e)+'ERRO ID - numlist')
# Filters based on max deviation allowed
def maxDev(Index,li,avg,max_deviation):
try:
retIn=[]
retli=[]
Index,li=__numlist(Index,li)
for ele in range(len(li)):
d=__diff(li[ele],avg)
if(d<=max_deviation):
retli.append(li[ele])
retIn.append(Index[ele])
else:
pass
return(retIn,retli)
except Exception as e:
print(str(e)+'ERROR ID - maxDev')
# Filters based on max deviation allowed
def minDev(Index,li,avg,max_deviation):
try:
retIn=[]
retli=[]
Index,li=__numlist(Index,li)
for ele in range(len(li)):
d=__diff(li[ele],avg)
if(d>max_deviation):
retli.append(li[ele])
retIn.append(Index[ele])
else:
pass
return(retIn,retli)
except Exception as e:
print(str(e)+'ERROR ID - minDev')
#checks if a parameter is of numtype
def __isnum(var):
try:
float(var)
return(True)
except:
return(False)
pass
#Filters data according to type
def __type_filter(Index,Data,Type):
try:
ret_index=[]
ret_data=[]
if(Type=='all'):
return(Index,Data)
if(Type!='num'):
for i in range(len(Data)):
if(type(Data[i])==Type):
ret_data.append(Data[i])
ret_index.append(Index[i])
return(ret_index,ret_data)
else:
for j in range(len(Data)):
if(__isnum(Data[j])==True):
ret_data.append(float(Data[j]))
ret_index.append(Index[j])
return(ret_index,ret_data)
except Exception as e:
print(str(e)+'ERROR ID - type_filter')
#filters a list based on a list of values or a single value
def __value_filter(Index,Data,Expected):
try:
if type(Expected) != type([]):
expected=[]
expected.append(Expected)
Expected=expected
pass
ret_data=[]
ret_index=[]
for i in range(len(Data)):
if(Data[i] in Expected):
ret_data.append(Data[i])
ret_index.append(Index[i])
return(ret_index,ret_data)
except Exception as e:
print(str(e)+'ERROR ID - value_filter')
#Removes all the '' from a code
def __remnull__(li):
try:
retli=[]
for i in range(len(li)):
if (li[i]!=''):
retli.append(li[i])
return(retli)
except Exception as e:
print(str(e)+'ERROR ID - remnull')
# Used to set the data within limits
def __limits(Index,Data,s,e):
try:
retli=[]
retIn=[]
for i in range(len(Data)):
if (Data[i]<=e) and (Data[i]>=s):
retli.append(Data[i])
retIn.append(Index[i])
return(retIn,retli)
except Exception as e:
print(str(e)+'ERROR ID - limits')
# Filters data recieved from arduino
def filter(hybrid=None,index=[],data=[],expected=[],expectedType=None,maxDeviation=None,minDeviation=None,closeTo=None,farFrom=None,numeric=True,limit=[],frequentAverage=False):
# Initialization
if expectedType!=None:
numeric=False
if hybrid!=None:
index,data=hybrid
if index!=[] and data==[]:
data=index.copy()
index=[]
data=list(data)
if index==[]:
index=[q for q in range(len(data))]
elif index!=[] and (len(index)!=len(data)):
print(f"index[] has {len(index)} elements while data[] has {len(data)} elements.\nMake sure both have equal number of elements !")
raise AssertionError
elif index!=[] and (len(index)==len(data)):
pass
if farFrom==None and closeTo!=None and maxDeviation !=None and minDeviation!= None:
farFrom = closeTo
if farFrom!=None and closeTo==None and maxDeviation !=None and minDeviation!= None:
closeTo=farFrom
# If data is numeric
if(numeric==True):
new_data=[]
new_index=[]
for i in range(len(data)):
try:
new_data.append(float(data[i]))
new_index.append(float(index[i]))
except:
pass
data=new_data.copy()
index=new_index.copy()
if (limit!=[]):
index,data=__limits(index,data,limit[0],limit[1])
pass
if closeTo!=None:
average=closeTo
elif __isunique(data)==False and frequentAverage==True:
average=most_frequent(data)
print(f'Average is most_frequent data = {average}')
elif(numeric==True) and frequentAverage==False:
average=sum(data)/len(data)
print(f'Average is calculated as {average}')
else:
if (numeric==True) and expected==[] and expectedType==None and closeTo == None and farFrom == None:
print("""
Not enough information to filter !!
Pass either limit , closeTo , expected , farFrom , minDeviation or maxDeviation""")
raise BaseException
# Average obtained
if expected!=[] :
index,data=__value_filter(index,data,expected)
pass
if expectedType!=None :
index,data=__type_filter(index,data,expectedType)
pass
if maxDeviation!=None :
index,data=maxDev(index,data,average,maxDeviation)
pass
if minDeviation!=None and (__isnum(farFrom)):
index,data=minDev(index,data,farFrom,minDeviation)
elif minDeviation!=None and (farFrom=="avg"):
index,data = minDev(index,data,average,minDeviation)
pass
if maxDeviation==None and closeTo!=None :
index,data=maxDev(index,data,average,1)
pass
if minDeviation==None and farFrom!=None :
index,data = minDev(index,data,farFrom,1)
return(index,data)
#Most frequent piece of data
def most_frequent(List):
try:
return (max(set(List), key = List.count))
except Exception as e:
print(str(e)+'ERROR ID - most_frequent')
#Least frequent piece of data
def least_frequent(List):
try:
return (min(set(List), key = List.count))
except Exception as e:
print(str(e)+'ERROR ID - least_frequent')
#Compresses data
def compress(li):
try:
if (type(li)!=type([])):
I,D=li
return(cpress(I,D))
else:
return([i for i,j in zip_longest(li,li[1:]) if i!=j])
except Exception as e:
print(str(e)+'ERROR ID - compress')
#Escapes from the escape Characters
def escape(string):
try:
li=__elements(string)
remli=['\b','\n','\r','\t']
retli=[]
for i in range(len(string)):
if((string[i] in remli)==False):
retli.append(string[i])
return("".join(retli))
except Exception as e:
print(str(e)+'ERROR ID - escape')
##############################################################################################################################################
##############################################################################################################################################
' Data Visualization FUNCTIONS: '
##############################################################################################################################################
##############################################################################################################################################
#Graphs the data
def Graph(hybrid=None,x=[],y=[],xlabel='dataPiece',ylabel='Amplitude',label='myData',color='red',title='Graph',markersize=7,stl='dark_background',d={},mark='x'):
try:
style.use(stl)
if hybrid != None:
x,y=hybrid
if d!={} and y==[] and x==[] :
replacementX=[]
replacementY=[]
for ele in d:
replacementX.append(ele)
replacementY.append(d[ele])
x=replacementX
y=replacementY
else:
if x!=[] and y==[]:
y=x.copy()
x=[i for i in range(len(y))]
elif x==[]:
x=[i for i in range(len(y))]
else:
pass
plt.plot(x,y,label=label,color=color, marker=mark,markersize=markersize)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
plt.legend()
plt.show()
except Exception as e:
print(str(e)+'ERROR ID - Graph')
# Used to compare two graphs
def compGraph(hybrid1=None,hybrid2=None,x1=[],y1=[],x2=[],y2=[],xlabel='dataPiece',ylabel='Amplitude',label1='myData-1',label2='myData-2',color1='red',color2='blue',title='Graph',markersize=7,stl='dark_background',fit=True,d1={},d2={}):
try:
if hybrid1 != None:
x1,y1=hybrid1
if hybrid2 != None:
x2,y2=hybrid2
style.use(stl)
if (d1!={} or d2!={})or (x1!=[] or x2!=[]):
fit=False
if d1!={}:
replacementX=[]
replacementY=[]
for ele1 in d1:
replacementX.append(ele1)
replacementY.append(d1[ele1])
x1=replacementX
y1=replacementY
if d2!={}:
replacementX=[]
replacementY=[]
for ele in d2:
replacementX.append(ele)
replacementY.append(d2[ele])
x2=replacementX
y2=replacementY
if fit == True:
def Map(a_value,frm,to):
percent=(a_value/frm) * 100
ret_value=(percent*to)/100
return(ret_value)
if x1 == []:
x1=[i for i in range(len(y1))]
if x2 == []:
x2=[j for j in range(len(y2))]
if(len(x1)>=len(x2)):
nli=[]
for p in range(len(x2)):
x2[p]=Map(x2[p],len(x2),len(x1))
else:
nli=[]
for p in range(len(x1)):
x1[p]=Map(x1[p],len(x1),len(x2))
plt.plot(x1,y1,label=label1,color=color1, marker="o",markersize=markersize,linewidth=2)
plt.plot(x2,y2,label=label2,color=color2, marker="x",markersize=markersize,linewidth=2)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(f"{title}\nWith Fit Enabled")
plt.legend()
plt.show()
else:
if x1 == [] :
x1=[i for i in range(len(y1))]
if x2 == [] :
x2=[j for j in range(len(y2))]
plt.plot(x1,y1,label=label1,color=color1, marker="o",markersize=markersize)
plt.plot(x2,y2,label=label2,color=color2, marker="x",markersize=markersize)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(f"{title}\nWith Fit Disabled")
plt.legend()
plt.show()
except Exception as e:
print(str(e)+'ERROR ID - compGraph')
##############################################################################################################################################
##############################################################################################################################################
' ARDUINO FUNCTIONS: '
##############################################################################################################################################
##############################################################################################################################################
# What this function does is it gets certain lines of data from a com port and removes the repeated values and also the escape sequence characters !!!
def ardata(COM,lines=50,baudrate=9600,timeout=1,squeeze=True,dynamic=False,msg='a',dynamicDelay=0.5,numeric=True):
try:
i=0
all=list()
if(type(COM)==type(1)):
ser=serial.Serial('COM{}'.format(COM),baudrate = baudrate, timeout=timeout)
else:
ser=serial.Serial('{}'.format(COM),baudrate = baudrate, timeout=timeout)
while(i<=lines):
if(dynamic==True):
ser.write(bytearray(msg,'utf-8'))
time.sleep(dynamicDelay)
all.append(escape(ser.readline().decode('ascii')))
time.sleep(0.1)
i+=1
all=__remnull__(all)
All=[]
if numeric==True:
for k in range(len(all)):
try:
All.append(float(all[k]))
except:
pass
else:
All=all
if(squeeze==False):
return(All)
else:
return(compress(All))
pass
except Exception as e:
print(str(e)+'ERROR ID - ardata')
#reads only one line of data from a comport:
def readSerial(COM,baudrate=9600,timeout=1):
try:
data=ardata(COM,2,baudrate,timeout,numeric=False)
return(data[0])
except Exception as e:
print(str(e)+'\nERROR ID - readSerial')
# writes only one line to a com port !
def writeSerial(COM,baudrate=9600,timeout=1,msg=""):
try:
ardata(COM,2,baudrate,timeout,dynamic=True,msg=msg)
except Exception as e:
print(str(e)+'\nERROR ID - writeSerial')
# to get a single dynamic communication between arduino and python !
def dynamicSerial(COM,baudrate=9600,timeout=1,msg="a",dynamicDelay=0.5):
try:
return(ardata(COM,2,baudrate,timeout,squeeze=False,dynamic=True,msg=msg,dynamicDelay=dynamicDelay))
except Exception as e:
print(str(e)+"\nERROR ID - dynamicSerial")
|
Arduino-Master-Delta
|
/Arduino_Master_Delta-404-py3-none-any.whl/Arduino_Master_Delta/Arduino_Master_Delta.py
|
Arduino_Master_Delta.py
|
# Arduino_Master Alpha Version 3.0
___
___
# What's new ?
#### >>> Added 6 new functions : readSerial, writeSerial, dynamicSerial, horizontal, vertical and marker.
#### >>> Fixed a bug that prevented direct access to pyserial functions without **`serial.`** prefix.
#### >>> ERROR ID that displays the part of code where something got wrong. It could be either due to your faulty inputs or a bug. In case of a bug, paste the error message in the comments along with the ERROR ID. This feature was added for easier bug elimination !
___
___
# Intro:
#### Embedded C is used to program microcontrollers like Arduino. However embedded C could never compete with Python's simplicity and functionality. Also Arduino being a microcontroller, we get a lot of garbage values which we require to filter before utilizing. This module eases the process of extracting and passing data to Arduino via Serial communication.
#### This Module also provides Easy and flexible Data Science functions for Data extraction, filtering, removing garbage values and Data Visualization !
___
___
# Installing via pip:
### Use the following command to install Arduino_Master using pip.
### **`pip install Arduino_Master`**
___
___
# Automatic Installation of other required Modules:
#### This module requires two more packages namely **`pyserial`** and **`matplotlib`**. Yet just by importing this module using the import statement or by using any function, unavailable modules will be installed and imported automatically. Make sure you have good internet connection and if still you get ModuleNotFound error, try installing these two modules manually via pip.
___
___
# Importing Functions:
#### **`from Arduino_Master import *`** statement is used to import all available functions from Arduino_Master. This version contains the following functions which we'll be discussing shortly. These functions can be grouped into 2 categories:
#### >> For Extracting and Writing data to Arduino:
#### $ ardata
#### $ readSerial
#### $ writeSerial
#### $ dynamicSerial
#### >> Data Science enabled functions for filtering and visualizing Data:
#### $ Graph
#### $ compGraph
#### $ horizontal
#### $ vertical
#### $ marker
#### $ most_frequent
#### $ least_frequent
#### $ compress
#### $ filter
___
___
# ardata():
#### ardata function is used to communicate with the arduino via Serial. This function returns a list of values available in the Serial port.
#### **`ardata(COM ,lines= 50 ,baudrate= 9600 ,timeout= 1 ,squeeze= True ,dynamic= False ,msg= 'a' ,dynamicDelay= 0.5 )`** is the function header.
___
## COM
#### **`COM`** parameter is used to specify the COM port to which arduino is connected to. You can pass either an integer or a string specifying the COM port.
### Eg:
```python
# COM parameter usage:
data = ardata(8) # or
data = ardata(COM=8)
#This will be interpreted as COM8
# If your COM port's name is not in this format, use the following:
data = ardata("YOUR_COM_PORT_NAME") #or
data = ardata(COM="YOUR_COM_PORT_NAME")
```
___
## lines
#### **`lines`** denotes the number of data units or lines it reads from the Serial monitor of Arduino. The default value is set to **50** which can be changed. Note that based on another parameter **`squeeze`**, the number of elements in the list this function returns might be lesser than the that of actual data.
___
## baudrate
#### **`baudrate`** parameter is used to specify the baudrate at which the Serial communication occurs at. The default value is **9600** which is the most widely used baudrate.
___
## timeout
#### **`timeout`** is used to specify the timeout value in seconds. The default value is **1**.
___
## squeeze
#### **`squeeze`** is used to specify if the data needs to be compressed. This uses a function from data science part of this module **`compress()`** which is used to remove **_repeated and sequential_** set of data with a single piece of data.
### Eg:
```python
# Consider the following list of data:
data = [ 1 , 2 , 2 , 2 , 3 , 3 , 5 , 1 , 1 , 2 , 5 , 5 ]
info = compress(data)
print(info)
# This will print [ 1 , 2 , 3 , 5 , 1 , 2 , 5 ]
```
#### **`squeeze`** uses the same function and takes either True (or) False boolean values as parameters. By default, this parameter is set to **True**. Referencing the above example code, if squeeze is set to **False**, ardata will retrun **data** and if it is set to **True** which is the default setting, it will return **info**.
___
## dynamic
#### **`dynamic`** is used to specify if the Serial communication is just to read from the serial port or for both reading and writing to the serial port. The default value is **false** which means you can only read from the Serial port. If dynamic is set to true, the string from the **`msg`** parameter will be written to the Serial port every time before reading a value.
___
## msg
#### **`msg`** parameter specifies the message that is to be written in the serial monitor. the default value is **'a'**. *It is a must to pas this parameter if dynamic is set to true.*
___
## dynamicDelay
#### **`dynamicDelay`** is used to specify the time this program has to wait after writing a value to the console and to start reading from the COM port. It is experimentally determined that a delay of 0.5 seconds is mandatory in order to prevent overlapping of passed messages.
___
> Note: ardata() reads one line at a time and hence Serial.println() should be used while coding Arduino and make sure there are no unnecessary Serial.print() or Serial.println() statements present in the code.
___
### Demo:
### 1) One way communication: With dynamic set to False
```C
// Code uploaded to Arduino
int check = 2;
void setup() {
Serial.begin(9600);
pinMode(check,INPUT);
}
void loop() {
if(digitalRead(check)==HIGH)
Serial.println("HIGH");
else
Serial.println("LOW");
delay(500);
}
```
```python
# Python code:
from Arduino_Master import *
# info contains complete data
info = ardata(8,squeeze=False)
print(f"{len(info)}=>{info}")
#compressed info contains compresses form of data
CompressedInfo = compress(info)
print(f"{len(CompressedInfo)}=>{CompressedInfo}")
'''
Output:
50=>['LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'LOW', 'LOW', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW']
5=>['LOW', 'HIGH', 'LOW', 'HIGH', 'LOW']
Thus actual data contains 50 elements whereas compresses data contains only 5 elements yet represents the outline of the data.
if info = ardata(8) was used instead, we would get the compressed version of data here represented by CompressedInfo.
'''
```
___
### 2) Two way communication: With dynamic set to True
```Code
// Code uploaded to Arduino
int check = 2;
void setup() {
Serial.begin(9600);
pinMode(check,INPUT);
}
void loop() {
if(Serial.available()>0)
{
if(Serial.readString()=="State")
{
if(digitalRead(check)==HIGH)
Serial.println("HIGH");
else
Serial.println("LOW");
}
delay(500);
}
}
// This code will print the result on the serial monitor only if "State" is sent to the serial monitor
```
```python
# Python code
from Arduino_Master import *
info = ardata(8,dynamic=True,msg="State")
print(info)
'''
This would print
['LOW', 'HIGH', 'LOW', 'HIGH', 'LOW', 'HIGH']
Since squeeze by default is set to True, data is compressed!
'''
```
### Though both these demonstrations are used to extract data from Arduino, the later is better than the former. The reason is that when dynamic is set to True, we ask for instantaneous information whereas when dynamic is set to False, there is a possibility of getting initial data alone rather than instantaneous data since arduino keeps writing the values to the Serial monitor.
### The functionality being inherited from pyserial, It is possible to call all functions from pyserial module without prefixing the functions with 'serial.' statement.
___
___
# readSerial
#### **`readSerial`** reads only one line from the Arduino.
#### **`readSerial( COM , baudrate = 9600 , timeout = 1 )`** is the function header.
| Parameters | Usage |
|------------|------|
| COM | Specify the COM port. Similar to ardata(), you can pass either an integer or the complete name as a string.|
| baudrate =9600| Set the baudrate. Default value is **9600**. |
| timeout =1| Set the timeout. Default is **1**|
#### returns a list with one element
___
___
# writeSerial()
#### **`writeSerial`** writes only one string to the Arduino's Serial monitor.
#### **`writeSerial(COM,baudrate=9600,timeout=1,msg="")`** is the function header.
| Parameters | Usage |
|------------|------|
| COM | Specify the COM port. Similar to ardata(), you can pass either an integer or the complete name as a string.|
| baudrate =9600| Set the baudrate. Default value is **9600**. |
| timeout = 1| Set the timeout. Default is **1**|
| msg = ""| String to be written to the Serial Port |
#### Returns nothing !
___
___
# dynamicSerial
#### **`dynamicSerial`** is similar to dynamic mode of ardata() except that this returns a **_list_** with just one element in it.
#### **`dynamicSerial( COM , baudrate = 9600 , timeout = 1 , msg = "a" , dynamicDelay = 0.5 )`** is the function header.
| Parameters | Usage |
|------------|------|
| COM | Specify the COM port. Similar to ardata(), you can pass either an integer or the complete name as a string.|
| baudrate =9600| Set the baudrate. Default value is **9600**. |
| timeout =1| Set the timeout. Default is **1**|
| msg ="a"| String to be written to the Serial Port |
| dynamicDelay = 0.5| Similar to that of ardata's dynamicDelay. Default value is set to **0.5 seconds**. Any value lesser than this would result in overlapping of the input. |
#### This function returns a list with only one element.
___
### Note:
#### For an arduino program that prints a value on Serial monitor only when we send it a value, the combination of writeSerial and readSerial functions won't work. dynamicSerial has to be used at that place.
```python
# Use
dynamicSerial(8,msg="Give DATA")
# INSTEAD OF
writeSerial(8,msg="Give Data")
data=readSerial(8)
# The latter would only return an empty list !!!
```
___
___
# Graph
#### **`Graph`** function is used to visualize a list of data.
#### **`Graph( y= None ,xlabel= 'dataPiece' ,ylabel= 'Amplitude' ,label= 'myData' ,color= 'red' ,title= 'Graph' ,markersize= 7 ,stl= 'ggplot' ,d= {} ,mark= 'x' )`** is the function header.
| Parameters | Usage |
|--------------|---------|
| y = None | Pass a list of values to be plotted along the y-axis. The x-axis is automatically generated depending on the number of parameters in your given list.|
| xlabel = 'dataPiece' | Used to label the X-axis legend |
| ylabel = 'Amplitude' | Used to label the Y-axis legend |
| label = 'myData' | What you want your data to be called |
| color = 'red' | What color you want your data to be plotted with |
| title = 'Graph' | Name of the graph |
| mark = 'x' | Used to set the marker type. Refer this StyleSheet => [Marker_Style_Sheet](https://matplotlib.org/3.1.0/api/markers_api.html) |
| markersize = 7| Size of the plotting line. |
| stl = 'ggplot' | Style of Graph you wish. Refer this StyleSheet => [StyleSheet](https://matplotlib.org/3.1.0/gallery/style_sheets/style_sheets_reference.html) |
| d = {} | Used to pass a dictionary. This is used only when you need custom x values instead of default sequentially arranged X-values. y and d must not be passed together. |
#### Passing Strings to y (or) Dictionaries whose values are strings will also be plotted accordingly !
___
### Demo:
### Demonstration 1: Passing a list to y
```Python
# Python Code
myList = [ 1 , 2 , 3 , 4 , 5 , 1 , 7 , 7 , 10 , 8]
Graph(myList,stl='dark_background')
```
### Output:

___
### Demonstration 2: Plotting using a dictionary to get custom X-values.
```Python
# Python Code
myDict = { 0:10 , 1:12 , 2:12.05 , 3:-0.1 , 4:-12.05 , 5:0 , 6:5 , 6:5 , 10:5.5 }
Graph(d=myDict)
```
### Output:

___
### Demonstration 3: Plotting Strings:
```pytho
# Python code
listOfStrings = ['LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'LOW', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'LOW', 'LOW', 'HIGH', 'HIGH']
Graph(listOfStrings)
```
### Output:

#### The same can also be done by passing a Dictionary !
___
___
# compGraph
#### **`compGraph`** is used to compare two sets of data ( 2 lists or 2 dictionaries or 1 list with 1 dictionary)
#### **`compGraph( y= None ,y2= None ,xlabel= 'dataPiece' ,ylabel= 'Amplitude' ,label1= 'myData-1' ,label2= 'myData-2' ,color1= 'red' ,color2= 'blue' ,title= 'Graph' ,markersize= 7 ,stl= 'ggplot' ,fit= True ,d1= {} ,d2= {} `)** is the function header.
| Parameters | Usage |
|--------------|---------|
| y = None | Pass a list of values to be plotted along the y-axis. The x-axis is automatically generated depending on the number of parameters in your given list.|
| xlabel = 'dataPiece' | Used to label the X-axis legend |
| ylabel = 'Amplitude' | Used to label the Y-axis legend |
| label1 = 'myData-1' | What you want your first set data to be called |
| label2 = 'myData-2' | What you want your second set data to be called |
| color1 = 'red' | What color you want your first set of data to be plotted with |
| color2 = 'blue' | What color you want your second set of data to be plotted with |
| title = 'Graph' | Name of the graph |
| markersize = 7| Size of the plotting line. |
| stl = 'ggplot' | Style of Graph you wish. Refer this StyleSheet => [StyleSheet](https://matplotlib.org/3.1.0/gallery/style_sheets/style_sheets_reference.html) |
| d1 = {} | Used to pass a dictionary as the first set of data. This is used only when you need custom x values instead of default sequentially arranged X-values. y and d1 must not be passed together. |
| d2 = {} | Used to pass a dictionary as the second set of data. This is used only when you need custom x values instead of default sequentially arranged X-values. y2 and d2 must not be passed together. |
| fit = True | A bit complex, and hence explained below |
___
## fit
#### **`fit`** parameter is used to specify if both the graphs need to be scaled to the maximum size or not. When y and y2 values have different number of elements **`fit = True`** enables changing X-values of the list of data which has less number of elements to equalize and approximate the correctness of distribution of data.
### With Fit **Disabled (left)** and With Fit **Enabled (right)**

#### In the above pics, the red colored data represents raw_data and blue colored data represents filtered data. So naturally filtered set of data will have less number of elements in it and if compGraph() function is used the result would be similar to the left Graph which looks a bit absurd. When **fit = True** enables data to fit into the whole graph without affecting the Amplitude of the data. In simple words, smaller list of data is stretched to the size of the bigger list of data along the X-axis to give an **_approximation_** without using dictionaries which are comparatively difficult to use than lists so as to make the functions newbie friendly.
#### compGraph is similar to Graph function just with visualizing one more list of data
___
___
# horizontal
#### Creates a line parallel to X-axis.
#### **`horizontal( y , lbl = 'marker' , start = 0 , end = 10 )`** is the function header.
|Parameter| Usage|
|---------|------|
|y|The distance from the origin is specified here|
|lbl = 'marker'|label is set to 'marker' by default|
|start = 0| value from which this line should start|
|end = 10 | value at which this line should end |
# Use this function before the Graph() function you wish the line to plotted in.
___
___
# vertical
#### Creates a line parallel to Y-axis.
#### **`vertical( x , lbl = 'marker' , start = 0 , end = 10 )`** is the function header.
|Parameter| Usage|
|---------|------|
|x|The distance from the origin is specified here|
|lbl = 'marker'|label is set to 'marker' by default|
|start = 0| value from which this line should start|
|end = 10 | value at which this line should end |
#### Use this function before the Graph() function you wish the line to plotted in.
___
### vertical and horizontal are used as markers in a graph and are always black in color !
```Python
vertical(5)
horizontal(5)
Graph([1,2,3,4,5,6,7,8,9,10])
# This would result in the following Graph
```

___
# marker
#### **`marker`** function creates a plus shaped plot at a given co-ordinate.
#### **`marker( x , y , limit = 1 , lbl = "marker" )`** is the function header.
|Parameter| Usage|
|---------|------|
|x|X Coordinate|
|y|Y Coordinate|
|limit=1| size of the marker|
|lbl='marker'|specify a label|
#### Use this function before the Graph() function you wish this marker to be plotted
```python
marker(5,6)
Graph([1,2,3,4,5,6,7,8,9,10])
# This would result in the following Graph
```

___
___
# most_frequent
#### **`most_frequent`** is used to return the most frequently occurring element in a given list.
#### **`most_frequent(List)`** is the function header. Just pass a list as a parameter, and it will return the most repeated element in the given list.
___
# least_frequent
#### **`least_frequent`** is used to return the least frequently occurring element in a given list.
#### **`least_frequent(List)`** is the function header. Just pass a list as a parameter, and it will return the least repeated element in the given list.
___
___
# compress
#### **`compress()`** which is used to remove **_repeated and sequential_** set of data with a single piece of data.
#### **`compress(li)`** is the function header.

#### In the above pic, red colored plot refers to the actual, uncompressed data while blue represents compressed data. As you can see the only purpose of compress is to show the trend of data and since Fit is enabled, an approximation of data is shown. In simple words, **`compress`** replaces continuous equivalent elements by a single element. **`compress`** is used only to visualize how many times a data piece varies to and fro and hence just an approximation. The next pics also has the same color representation as of before and demonstrates **`compress()`** function !


___
___
# filter
#### filter function is used to remove unnecessary data from a list.**_This function is only compatible with lists. Next version might have its compatibility increased to Dictionaries too._**
#### **`filter(data ,expected= [] ,expected_type= None ,max_deviation= None ,closeTo= None ,numeric= True ,limit= [] )`** is the function header.
| Parameters | Usage |
|--------------|---------|
| data | This parameter accepts a list. |
| expected = [ ] | Pass a list of expected elements that you need in the filtered list |
| expected_type = [ ] | Filters data based on the type. You can pass the following as arguements : int , float , str , 'num' , 'all'. Note that **num** and **all** alone are placed within single quotes since they are custom made types. 'num' denotes all numeric data like int and float. 'all' denotes all kinds of data.|
|max_deviation = None| Permitted maximum deviation from calculated average. |
|closeTo = None| Used to find data close to the given arguement. If closeTo alone is used without max_deviation, then max_deviation is taken as 1 by default. |
|numeric = True| Used to specify if you are looking for numeric data for calculation. If you wish to have strings of data in your filtered list make sure you set numeric to False. |
|limit = [ ]| Used to specify filter out garbage values! It basically means, no matter what, the data would not have gone beyond these limits. If it did, it is a Garbage Value. The format is **_limit=[ start-limit , end-limit ]_** |
### Why and How average is calculated ?
#### While filtering data with max_deviation, a value has to be specified from which the upper and lower limits containing data are filter.(i.e.) if max_deviation is 1.5, data is filtered such that only data within +(or)- 1.5 than average is present in the filtered data.
### This is how average is calculated.
#### If closeTo value is present, closeTo is taken as average.
#### If closeTo value is not passed, the most frequent data piece in the list of data is taken as average.
#### If closeTo is not passed as well as all the elements in the given data are unique, average is calculated in the conventional way. But with huge garbage values, the average would shift so much that no data remains in that area returning an empty list. For that when limit parameter is passed, garbage values are filtered out earlier before other calculations take place.
# Depending on the number of lines you need to read, time you need to wait will increase !!!
# Garbage values occur when your arduino's pins come in contact with each other. No matter if it is a cloth or your hand, arduino is sensitive enough to sense it and give you garbage values !!
___
# Demo:
# Garbage Value Removal:
```C
String msg;
const int trigPin = 9;
const int echoPin = 10;
double duration;
float distance;
void setup()
{
Serial.begin(9600);
pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
}
void loop()
// If information is available in Serial port from arduino get it and then checking for the distance
{ if (Serial.available()>0)
{
msg=Serial.readString() ;
if(msg=="d")
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration/29/2;
Serial.println(distance);
}
else
int i=0; // Just Do nothing.....(Never Mind statement !!! )
}
}
```
___
```Python
# importing area !!
from Arduino_Master import *
# collecting data and saving it as a list in info
info=filter(ardata(8,squeeze=False,dynamic=True,msg="d",lines=50),expected_type="num")
# adding garbage values for checking purpose
info.insert(7,7000)
info.insert(8,4500)
# Removing all the repeating elements in order to test the average function !!!
# Since the data is from an Ultrasonic sensor, Its limit is known and it is 2 metre or 200 cm
Info=filter(list(set(info)),max_deviation=4,limit=[0,200])
print(info)
print(Info)
Graph(info)
Graph(Info)
compGraph(info,Info)
```
___

### Without any filter, The above pic displays the data from Arduino with custom added garbage values in order to test.
___

### Data after filtering is displayed above !! Thus conventional average works fine !!
___

### Comparison of data is displayed above. Since the limits of the sensor were specified, values as high as 4500 and 6000 were removed and then the average was calculated making this module a well built one. Red is raw data whereas Blue is filtered data.
___
## If used correctly, you can filter your data in the following ways !!!

### Check light intensity and with previously measured values, you can check if the light is switched on or not just using an LDR.
### Learn how to plot a Graph like this using Arduino_Master through this link : [Plotting light intensity using Arduino_Master](https://www.instructables.com/id/Light-Intensity-Plotting-Using-Arduino-and-Pythons/)
___

### Impulse removal Example in the above pic
___

### You can also detect and measure impulses !!!
___
___
# Developed by SAYAD PERVEZ !!!
# Trust me Am just 17.
# EmailID : [[email protected]]
|
Arduino-Master
|
/Arduino_Master-3.tar.gz/Arduino_Master-3/README.md
|
README.md
|
def __cmd__(command):
try:
import os
os.system(command)
except Exception as e:
print("Something went wrong in accessing the command line. This feature was well tested on Windows OS.\n This part belongs to importing of modules if they are not installed in your computer yet.\nTry installing matplotlib and pyserial manually via pip.\nAutomatic installation fail due to unaccessable command line !\n")
print(e)
def __installationCheck__():
try:
import serial
Module_1=True
except Exception:
Module_1=False
print("pyserial module not found.\nDon't worry, we'll install it in your pc automatically.\nJust make sure you have good internet connection !!")
try:
import matplotlib
Module_2=True
except Exception:
Module_2=False
print("matplotlib module not found.\nDon't worry, we'll install it in your pc automatically.\nJust make sure you have good internet connection !!")
return(1 if (Module_1 & Module_2)==True else 0)
def __installModules__():
try:
__cmd__("pip install pyserial")
__cmd__("pip install matplotlib")
except Exception as e:
print(e)
def __modulesInitialization__():
n=1
while(__installationCheck__()!=1):
__installModules__()
if(n>3):
print("This module consists auto-pip package installation yet unable to download 'matplotlib' and 'pyserial'")
print("Try switching on your internet connection or download those two modules via pip manually")
raise ModuleNotFoundError
break
n+=1
return
__modulesInitialization__()
import time
from itertools import zip_longest as zip_longest
import serial
from serial import *
import matplotlib.pyplot as plt
from matplotlib import style
# You know what I do
def __elements(g_string):
try:
gstring=str(g_string)
ng=len(gstring)-1
lg=list()
ig=0
while(ig<=ng):
lg.append(gstring[ig])
ig+=1
return(lg)
except Exception as e:
print(str(e)+'\n ERROR ID - elements')
# Checks if all the elements in the given list are unique
def __isunique(Data):
try:
nData=len(Data)
nSet =len(list(set(Data)))
if(nData==nSet):
return(True)
else:
return(False)
except Exception as e:
print(str(e)+'\nERROR ID - isunique')
# draws a line parallel to y axis
def horizontal(y,lbl='marker',start=0,end=10):
try:
plt.plot([start,end],[y,y],label=lbl,linewidth=2,color='black')
except Exception as e:
print(str(e)+'\nERROR ID - yline')
# draws a line parallel to x axis.
def vertical(x,lbl='marker',start=0,end=10):
try:
plt.plot([x,x],[start,end],label=lbl,linewidth=2,color='black')
except Exception as e:
print(str(e)+'\nERROR ID - xline')
# Creates a marker:
def marker(x,y,limit=1,lbl="marker"):
vertical(x,lbl=lbl,start=y-limit,end=y+limit)
horizontal(y,lbl=lbl,start=x-limit,end=x+limit)
# Converts two lists into a dictionary
def __liDict(li1,li2):
try:
dictionary = dict(zip(li1,li2))
return(dictionary)
except Exception as e:
print(str(e)+'ERROR ID - lidict')
# Assigns a value to a string
def assignValue(str_list):
try:
key=list(set(str_list))
n=len(list(set(str_list)))//2
retLi=[]
if(len(list(set(str_list)))%2==0):
for i in range(-n+1,n+1):
retLi.append(i)
return(__liDict(key,retLi))
else:
for i in range(-n,n+1):
retLi.append(i)
return(__liDict(key,retLi))
except Exception as e:
print(str(e)+'ERROR ID - assignValue')
#finds the difference between two numbers
def __diff(x,y):
try:
return(abs(x-y))
except Exception as e:
print(str(e)+'ERROR ID - diff')
# Converts all the elements of the list to integers
def __numlist(li):
try:
retlist=[]
for a in range(len(li)):
retlist.append(float(li[a]))
return(retlist)
except Exception as e:
print(str(e)+'ERRO ID - numlist')
# Filters based on max deviation allowed
def maxDev(li,avg,max_deviation):
try:
retli=[]
li=__numlist(li)
for ele in range(len(li)):
d=__diff(li[ele],avg)
if(d<=max_deviation):
retli.append(li[ele])
else:
pass
return(retli)
except Exception as e:
print(str(e)+'ERROR ID - maxDev')
#checks if a parameter is of numtype
def __isnum(var):
try:
float(var)
return(True)
except:
return(False)
pass
#Filters data according to type
def __type_filter(Data,Type):
try:
ret_data=[]
if(Type=='all'):
return(Data)
if(Type!='num'):
for i in range(len(Data)):
if(type(Data[i])==Type):
ret_data.append(Data[i])
return(ret_data)
else:
for j in range(len(Data)):
if(__isnum(Data[j])==True):
ret_data.append(Data[j])
return(ret_data)
except Exception as e:
print(str(e)+'ERROR ID - type_filter')
#filters a list based on a list of values or a single value
def __value_filter(Data,Expected):
try:
if type(Expected) != type([]):
expected=[]
expected.append(Expected)
Expected=expected
pass
ret_data=[]
for i in range(len(Data)):
if(Data[i] in Expected):
ret_data.append(Data[i])
return(ret_data)
except Exception as e:
print(str(e)+'ERROR ID - value_filter')
#Removes all the '' from a code
def __remnull__(li):
try:
retli=[]
for i in range(len(li)):
if (li[i]!=''):
retli.append(li[i])
return(retli)
except Exception as e:
print(str(e)+'ERROR ID - remnull')
# Used to set the data within limits
def __limits(Data,s,e):
try:
retli=[]
for i in range(len(Data)):
if (Data[i]<=e) and (Data[i]>=s):
retli.append(Data[i])
return(retli)
except Exception as e:
print(str(e)+'ERROR ID - limits')
# Filters data recieved from arduino
def filter(data,expected=[],expected_type=None,max_deviation=None,closeTo=None,numeric=True,limit=[]):
data=list(data)
if(numeric==True):
new_data=[]
for i in range(len(data)):
try:
new_data.append(float(data[i]))
except:
pass
data=new_data
if (limit!=[]):
data=__limits(data,limit[0],limit[1])
pass
if closeTo!=None:
average=closeTo
elif __isunique(data)==False:
average=most_frequent(data)
print(f'Average is most_frequent data = {average}')
elif(numeric==True) and (limit!=[]):
average=sum(data)/len(data)
print(f'Average is calculated as {average}')
else:
if (numeric==True):
print("""
Not enough information to filter !!
Pass either limit , closeTo , expected or max_deviation""")
raise BaseException
# Average obtained
if expected!=[] :
data=__value_filter(data,expected)
pass
if expected_type!=None :
data=__type_filter(data,expected_type)
pass
if max_deviation!=None :
data=maxDev(data,average,max_deviation)
pass
if max_deviation==None and closeTo!=None :
data=maxDev(data,average,1)
pass
return(data)
#Most frequent piece of data
def most_frequent(List):
try:
return (max(set(List), key = List.count))
except Exception as e:
print(str(e)+'ERROR ID - most_frequent')
#Least frequent piece of data
def least_frequent(List):
try:
return (min(set(List), key = List.count))
except Exception as e:
print(str(e)+'ERROR ID - least_frequent')
#Compresses data
def compress(li):
try:
return([i for i,j in zip_longest(li,li[1:]) if i!=j])
except Exception as e:
print(str(e)+'ERROR ID - compress')
#Escapes from the escape Characters
def escape(string):
try:
li=__elements(string)
remli=['\b','\n','\r','\t']
retli=[]
for i in range(len(string)):
if((string[i] in remli)==False):
retli.append(string[i])
return("".join(retli))
except Exception as e:
print(str(e)+'ERROR ID - escape')
#Graphs the data
def Graph(y=None,xlabel='dataPiece',ylabel='Amplitude',label='myData',color='red',title='Graph',markersize=7,stl='ggplot',d={},mark='x'):
try:
style.use(stl)
if d!={} and y==None:
replacementX=[]
replacementY=[]
for ele in d:
replacementX.append(ele)
replacementY.append(d[ele])
x=replacementX
y=replacementY
else:
x=[i for i in range(len(y))]
plt.plot(x,y,label=label,color=color, marker=mark,markersize=markersize)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
plt.legend()
plt.show()
except Exception as e:
print(str(e)+'ERROR ID - Graph')
# Used to compare two graphs
def compGraph(y=None,y2=None,xlabel='dataPiece',ylabel='Amplitude',label1='myData-1',label2='myData-2',color1='red',color2='blue',title='Graph',markersize=7,stl='ggplot',fit=True,d1={},d2={}):
try:
style.use(stl)
if d1!={} or d2!={}:
fit=False
if d1!={}:
replacementX=[]
replacementY=[]
for ele1 in d1:
replacementX.append(ele1)
replacementY.append(d1[ele1])
x=replacementX
y=replacementY
if d2!={}:
replacementX=[]
replacementY=[]
for ele in d2:
replacementX.append(ele)
replacementY.append(d2[ele])
x2=replacementX
y2=replacementY
if fit == True:
def Map(a_value,frm,to):
percent=(a_value/frm) * 100
ret_value=(percent*to)/100
return(ret_value)
x=[i for i in range(len(y))]
x2=[j for j in range(len(y2))]
if(len(x)>=len(x2)):
nli=[]
for p in range(len(x2)):
x2[p]=Map(x2[p],len(x2),len(x))
else:
nli=[]
for p in range(len(x)):
x[p]=Map(x[p],len(x),len(x2))
plt.plot(x,y,label=label1,color=color1, marker="o",markersize=markersize,linewidth=2)
plt.plot(x2,y2,label=label2,color=color2, marker="x",markersize=markersize,linewidth=2)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(f"{title}\nWith Fit Enabled")
plt.legend()
plt.show()
else:
x=[i for i in range(len(y))]
x2=[j for j in range(len(y2))]
plt.plot(x,y,label=label1,color=color1, marker="o",markersize=markersize)
plt.plot(x2,y2,label=label2,color=color2, marker="x",markersize=markersize)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(f"{title}\nWith Fit Disabled")
plt.legend()
plt.show()
except Exception as e:
print(str(e)+'ERROR ID - compGraph')
# What this function does is it gets certain lines of data from a com port and removes the repeated values and also the escape sequence characters !!!
def ardata(COM,lines=50,baudrate=9600,timeout=1,squeeze=True,dynamic=False,msg='a',dynamicDelay=0.5):
try:
i=0
all=list()
if(type(COM)==type(1)):
ser=serial.Serial('COM{}'.format(COM),baudrate = baudrate, timeout=timeout)
else:
ser=serial.Serial('{}'.format(COM),baudrate = baudrate, timeout=timeout)
while(i<=lines):
if(dynamic==True):
ser.write(bytearray(msg,'utf-8'))
time.sleep(dynamicDelay)
all.append(escape(ser.readline().decode('ascii')))
time.sleep(0.1)
i+=1
all=__remnull__(all)
if(squeeze==False):
return(all)
else:
return(compress(all))
pass
except Exception as e:
print(str(e)+'ERROR ID - ardata')
#reads only one line of data from a comport:
def readSerial(COM,baudrate=9600,timeout=1):
try:
data=ardata(COM,1,baudrate,timeout)
return(data)
except Exception as e:
print(str(e)+'\nERROR ID - readSerial')
# writes only one line to a com port !
def writeSerial(COM,baudrate=9600,timeout=1,msg=""):
try:
ardata(COM,1,baudrate,timeout,dynamic=True,msg=msg)
except Exception as e:
print(str(e)+'\nERROR ID - writeSerial')
# to get a single dynamic communication between arduino and python !
def dynamicSerial(COM,baudrate=9600,timeout=1,msg="a",dynamicDelay=0.5):
try:
return(ardata(COM,1,baudrate,timeout,squeeze=False,dynamic=True,msg=msg,dynamicDelay=dynamicDelay))
except Exception as e:
print(str(e)+"\nERROR ID - dynamicSerial")
|
Arduino-Master
|
/Arduino_Master-3.tar.gz/Arduino_Master-3/Arduino_Master/Arduino_Master.py
|
Arduino_Master.py
|
import os
import serial
class hooker:
def __init__(self,port="COM3",baudRate=9600,file_name='test.ino',folder_name = 'test') -> None:
self.serialPort = port
self.baudRate = baudRate
self.file_name = file_name
self.folder_name = folder_name
self.receive_message = ""
self.send_message = ""
self.ser = ''
# 0 basic operations
def open_ser(self):
self.ser = serial.Serial(self.serialPort,self.baudRate,timeout = 0.5)
print("参数设置:串口=%s ,波特率=%d" % (self.serialPort, self.baudRate))
def close_ser(self):
self.ser.close()
def ab_file_path(self):
return self.folder_name + '//' + self.file_name
def burn(self,file):
#upload the code into arduino
command = r".\arduino-cli upload -b arduino:avr:uno -p" + self.serialPort + ' ' + file
return os.system(command)
def compile(self,file):
#compile the code
command = r'.\arduino-cli compile -b arduino:avr:uno ' + eval(repr(file))
print(command)
return os.system(command)
# 1 receive the message from arduino
def receive(self):
while(1):
self.read_once()
def read_once(self):
self.receive_message = self.ser.readline().strip().decode('utf-8','ignore')
if self.receive_message!="":
#print("receive from arduino: " + self.receive_message)
pass
return self.receive_message
#2 write to arduino
def write_once(self,command=''):
if command =='':
self.ser.write(self.send_message.encode())
else:
#print("send to arduino: " + command)
self.ser.write(command.encode())
def send(self):
while(1):
if self.send_message != "":
self.write_once()
print("send to arduino: " + self.send_message)
self.send_message = ""
if __name__ == "__main__":
import time
h = hooker()
h.open_ser()
time.sleep(3)
h.send_message = "c\n"
h.write_once()
h.send_message = "p\n"
h.write_once()
h.receive()
|
Arduino-debuger
|
/Arduino%20debuger-1.0.0.tar.zip/debugerv2/arduinohooker.py
|
arduinohooker.py
|
# 使用手册:
## 一、调试命令集合
### lx
*使用例子*:l32:
打印接下来32行代码。如果剩余代码<32行,则把剩余代码全部打印。
x可缺省。缺省时,默认打印接下来7行代码
lall:打印完整代码
lthis:打印**接下来要执行**的某一行
### c
继续运行代码
### p
暂停代码执行。点击回车后打印出暂停后**接下来要执行的**一行代码
### s
执行下一行指令。点击回车后,打印出**刚刚执行过**的指令。
### n
执行下一行指令,若下一行指令是函数,则跳过函数执行结果。
### g-variable-value
将某个variable改变为特定value的值
### d-variable
打印某个variable的值
## 二、使用方法
arduino-cli compile -b arduino:avr:uno C:\Users\xingxing\Documents\Arduino\button2
arduino-cli upload -b arduino:avr:uno -p COM3 C:\Users\xingxing\Documents\Arduino\button2
|
Arduino-debuger
|
/Arduino%20debuger-1.0.0.tar.zip/debugerv2/readme.md
|
readme.md
|
import commandhooker
import interpreter as inter
import arduinohooker as ah
import op
import struct
import sys
from multiprocessing import Process,Pipe
from ctypes import *
from commandhooker import Colored
color = Colored()
size_dict = {
'int':2,
'float':4,
'double':4,
'char':1
}
short_list = {
'int':'h',
'float':'f',
'double':'d',
'char':'c'
}
temp = []
no_variable = 0
db = 0 # if db == 1, then addr of function_list.variable_list[no_variable]
# need to be refreshed
# if db == 2 then current line need to be refreshed
source = []
#-----those three should be given by command------
#-------------------------------------------------
class debuger:
def __init__(self,port,baud_rate,folder,file) -> None:
self.arduino = ah.hooker(folder_name=folder,file_name=file,baudRate=baud_rate,port=port)
self.programmer = commandhooker.user()
self.temp_folder = ""
self.arduino_current_func = ""
self.arduino_current_line = 0
self.arduino_current_variable = inter.default_variable #the variable is under checking
self.function_list = []
self.state = "p"
self.source = inter.read_source(self.arduino.ab_file_path())
# state:
# 1/ w state information from arduino will be interpret as value of variable
# 2/ b state ....... interpreted as breakpoint information
# 3/ p state next message will be line of the pause
# 4/ c state Serial.print already had in source code
def check(self):
global source
if(self.arduino.compile(self.arduino.ab_file_path())):
# if compile return 1, then the source file is wrong
raise Exception("Source file wrong.")
else:
# else the compile is alright
new_folder_path = self.arduino.folder_name+'//temp'
self.temp_folder = new_folder_path
op.mkdir(new_folder_path)
new_file_path = new_folder_path+'//'+'temp.ino'
op.copy('debuger.cpp',self.temp_folder+'//debuger.cpp')
op.copy('debuger.hpp',self.temp_folder+'//debuger.hpp')
self.function_list = inter.interpret(self.arduino.ab_file_path(),new_file_path)
op.save(self.function_list,'func.pkl')
self.arduino_current_func = self.function_list[1]#current function intialized as setup()
self.programmer.write_once("debug file has been generated at " + new_file_path)
if(self.arduino.compile(new_file_path) | self.arduino.burn(new_file_path)):
raise Exception("Uploading error")
else:
self.programmer.write_once(self.programmer.colors.green("Uploading successfully"))
def run(self):
receive,send = Pipe(True)
programmer_process = Process(target=self.handle,args=((receive,send),100))
programmer_process.start()
receive.close()
while(1):
message = input()
send.send(message)
#self.programmer.write_once("programmer type: " + message)
def handle(self,pipe,x):
self.arduino.open_ser()
print('\n>>>',end='')
receive,send = pipe
send.close()
while(1):
self.arduino.read_once()
if(self.arduino.receive_message != ""):
self.handle_message_from_arduino()
self.arduino.receive_message = ""
if(receive.poll()):
self.programmer.receive_message = receive.recv()
self.handle_message_from_programmer()
self.programmer.receive_message = ""
def handle_message_from_arduino(self):
global db
global no_variable
global temp
message = self.arduino.receive_message
#print(color.blue(message))
if self.state == 'c' or self.state == 'p' or self.state == 'w':
# it means the program is running
if message == "DEADBEEFfunc":
# if message = deadbeeffunc, then next message
# should be name of current running function
self.arduino_current_func = -1
no_variable = 0
db = 0
elif message == "DEADBEEF":
# in this situation, next message should be addr
# of next variable in current function
db = 1
no_variable += 1
elif message == "DEADBEEFline":
db = 2
else:
if(db == 1):
# which means this message must be addr of a variable
if no_variable > len(self.arduino_current_func.variable_list):
# then this addr must be global variables
self.function_list[0].\
variable_list[no_variable-len(self.arduino_current_func.variable_list)-1].addr\
= int(message)
else:
self.arduino_current_func.variable_list[no_variable-1].addr = int(message)
db = 0
elif(self.arduino_current_func == -1):
# which means this message must be name of a function
self.arduino_current_func = self.find_function(message)
elif(db == 2):
# which means now the program jumps another line, current line need to be refreshed
self.arduino_current_line = int(message)
#print(self.arduino_current_line)
db = 0
else:
# it's must be Serial.print of origin source code,but we don't allow.
# self.programmer.write_once(message)
pass
elif self.state == 'b':
if message == '0':
self.programmer.write_once("No breakpoint Yet" + '\n ')
print('>>>',end='')
elif message.isdigit():
self.programmer.write_once("breakpoint at line " + message + '\n ')
print('>>>',end='')
else:
pass
else:
if message == "W":
db = 3
elif message == 'w':
result = self.turn(self.arduino_current_variable.type)
self.programmer.write_once(result)
print('>>>',end='')
self.arduino_current_variable = inter.default_variable
temp = []
db = 0
elif(db == 3):
# which means the programmer now wants to watch value of a variable
temp.append(message)
def handle_message_from_programmer(self):
global temp
message = self.programmer.receive_message
message.strip()
if message == '':
print('>>>',end='')
return
if(message[0] == 'b'):
# below code seems to be a little tedious,
# but it can check whether the command is valid.
self.state = 'b'
if ('+' in message):
message = message.replace(' ','')
number = message[message.index('+')+1:]
if number.isdigit():
self.arduino.write_once('b+'+ number + '\n')
else:
self.programmer.write_once("Invalid command!")
print('>>>',end='')
elif ('-' in message):
message = message.replace(' ','')
number = message[message.index('-')+1:]
if number.isdigit():
self.arduino.write_once('b-'+ number + '\n')
else:
self.programmer.write_once("Invalid command!")
print('>>>',end='')
elif ('info' in message):
self.arduino.write_once("b info\n")
else:
self.programmer.write_once("Invalid command!")
print('>>>',end='')
elif(message == 'c'):
self.state = 'c'
self.arduino.write_once(message + '\n')
self.programmer.write_once('program running...\n')
print('>>>',end='')
elif(message == 's'):
self.arduino.write_once(message + '\n')
print(color.red(str(self.arduino_current_line)))
self.programmer.write_once(str(self.arduino_current_line) + '-->' + self.source[self.arduino_current_line-1].content)
print('>>>',end='')
elif(message == 'p'):
if self.state == 'p':
self.programmer.write_once('program has been paused!')
print('>>>',end='')
return
self.state = 'p'
self.arduino.write_once('p')
times = 15
while(times>0):
#print(color.red(self.arduino.read_once()))
self.arduino.read_once()
if(self.arduino.receive_message!=''):
self.handle_message_from_arduino()
self.arduino.receive_message = ''
times-=1
self.programmer.write_once("pause at " + self.arduino.ab_file_path() + ", line " + str(self.arduino_current_line)\
+ '\n' + self.find_line(self.arduino_current_line).content)
print('>>>',end='')
elif(message[0] == 'n'):
if self.is_func_declaration(self.arduino_current_line):
# when the line is in a certain function, then we write 's' until stepping out of the function
l = self.arduino_current_line
func = self.arduino_current_func
self.arduino.write_once('s\n')
threshold = 3
while(threshold>0):
if(self.arduino.read_once() == ''):
threshold-=1
else:
self.handle_message_from_arduino()
while(self.arduino_current_line >= func.difination[0].line and \
self.arduino_current_line <= func.difination[1].line):
self.arduino.write_once('s\n')
threshold = 1
while(threshold>0):
if(self.arduino.read_once() == ''):
threshold-=1
else:
self.handle_message_from_arduino()
self.programmer.write_once(str(l) + '-->' + self.source[l-1].content)
print('>>>',end='')
else:
self.arduino.write_once("s\n")
self.programmer.write_once(str(self.arduino_current_line) + '-->' + self.source[self.arduino_current_line-1].content)
print('>>>',end='')
elif(message[0] == 'w'):
if message.find('-') == -1:
self.programmer.write_once("Invalid command!")
print('>>>',end='')
return
flag = 0
for m in message.split('-')[1:]:
if not m.isdigit():
self.programmer.write_once("Invalid command!")
print('>>>',end='')
flag = 1
break
if(not flag):
self.arduino.write_once(message + '\n')
while( (message:=self.arduino.read_once()) != 'w' ):
if message.isdigit():
self.programmer.write_once(message)
else:
flag = 0
elif(message[0] == 'm'):
if message.find('-') == -1:
self.programmer.write_once("Invalid command!")
print('>>>',end='')
return
flag = 0
for m in message.split('-')[1:]:
if not m.isdigit():
self.programmer.write_once("Invalid command!")
print('>>>',end='')
flag = 1
break
if int(message.split('-')[2])>255:
self.programmer.write_once("Target number is bigger than 255")
print('>>>',end='')
flag = 1
if(not flag):
self.arduino.write_once(message + '\n')
else:
flag = 0
elif(message[0] == 'd'):
self.state = 'w'
if message.find('-') == -1:
self.programmer.write_once("Invalid command!")
print('>>>',end='')
return
variable = message.split('-')[1]
if((index:=variable.find('['))!=-1):
#when the variable is certain element of a array, then we need get rid of '['
#like d-a[12]:check value of a[12], the value name is a[12], but the true name should be a
variable = variable[:index]
if (v:=self.find_variable_in_function(self.arduino_current_func,variable))!=-1\
or (v:=self.find_variable_in_function(self.function_list[0],variable))!=-1:
self.arduino_current_variable = v
if type(v) == type(inter.default_variable):
# its a variable
addr = v.addr
if addr == 0:
self.programmer.write_once("Varaible has not been initialezed")
print('>>>',end='')
return
size = size_dict[v.type]
command = "w-"+str(addr)+'-'+str(size)
self.arduino.write_once(command)
while(1):
value = self.arduino.read_once()
if(value == "w"):
break
elif (value == "W" or value == ''):
continue
else:
temp.append(value)
result = self.turn(v.type)
self.programmer.write_once(result)
print('>>>',end='')
else:
#its an array
# two kinds of input: say there is an array a[10]
# 1 programmer input: a
# then we need print every element of it.
# 2 programmer a[10]
# then we need print 10th element of it.
if (index:=message.find('['))!=-1:
index2 = message.find(']')
number = int(message[index+1:index2])
size = size_dict[v.type]
if number<v.length and number>-1:
addr = v.addr + size*number
command = "w-"+str(addr)+'-'+str(size)
self.arduino.write_once(command)
while(1):
value = self.arduino.read_once()
if(value == "w"):
break
elif (value == "W" or value == ''):
continue
else:
temp.append(value)
result = self.turn(v.type)
self.programmer.write_once(result)
print('>>>',end='')
else:
self.programmer.write_once("length is out of range")
print('>>>',end='')
else:
size = size_dict[v.type]
for i in range(v.length):
addr = v.addr + i*size
command = "w-"+str(addr)+'-'+str(size)
self.arduino.write_once(command)
# when switch = 1, receive value from arduino and save it in temp
# when switch = 0, then next information will be "w" or "W"
while(1):
value = self.arduino.read_once()
if(value == "w"):
break
elif (value == "W" or value == ''):
continue
else:
temp.append(value)
result = self.turn(v.type)
self.programmer.write_once(result)
print('>>>',end='')
else:
self.programmer.write_once("Variable not found")
print('>>>',end='')
elif(message[0] == 'g'):
if message.find('-') == -1:
self.programmer.write_once("Invalid command!")
print('>>>',end='')
return
l = message.split('-')
if len(l)<=2:
self.programmer.write_once("Invalid command")
print('>>>',end='')
return
variable = l[1]
if (index:=variable.find('['))!=-1:
variable = variable[:index]
value = eval(l[2])
number = 0
if (v:=self.find_variable_in_function(self.arduino_current_func,variable))!=-1\
or (v:=self.find_variable_in_function(self.function_list[0],variable))!=-1:
if message.find('[')!=-1:
#its an array
index1 = message.find('[')
index2 = message.find(']')
number = int(message[index1+1:index2])
self.arduino_current_variable = v
if str(type(value)).find(v.type)!= -1:
byte_list = bin(int.from_bytes(struct.pack(short_list[v.type],value),sys.byteorder))
byte_list = byte_list[2:]
byte_list = (size_dict[v.type]*8-len(byte_list))*'0' + byte_list # make up for
# every time 8 bits, send the data
for i in range(0,size_dict[v.type]):
byte = int(byte_list[i*8:(i+1)*8],2)
command = "m-"+str(v.addr+number*size_dict[v.type]+size_dict[v.type]-i-1)+'-'+str(byte)
self.arduino.write_once(command +'\n')
# time.sleep(0.1)
self.programmer.write_once('done')
print('>>>',end='')
else:
self.programmer.write_once("value should be the same type as variable")
print('>>>',end='')
elif(message[0] == 'l'):
if message == 'lall':
for content in self.source:
print_content = str(self.source.index(content)+1) + '-->' + content.content
self.programmer.write_once(print_content)
return
if message == 'lthis':
print(color.red(str(self.arduino_current_line)))
print_content = str(self.arduino_current_line) + '-->' + self.source[self.arduino_current_line-1].content
self.programmer.write_once(print_content)
print(">>>",end='')
return
if len(message) == 1:
line_num = 7
elif message[1:].isdigit():
line_num = int(message[1:])
else:
self.programmer.write_once('lx x is number of lines you want to print out')
print(">>>",end="")
return
for i in range(line_num):
#print next seven lines
try:
print_content = str(self.arduino_current_line+i) + '-->' + self.source[self.arduino_current_line+i].content
self.programmer.write_once(print_content)
except:
# if current line is the last few lines of the program, then we can't print "next seven lines".
break
print('>>>',end='')
else:
try:
try:
print(eval(message))
except:
eval(message)
print('>>>',end='')
except:
self.programmer.write_once("Invalid expression")
print('>>>',end='')
def debug(self):
print('Debuger developed by fatdog xie')
self.check()
self.run()
# tool-functions
def find_variable_in_function(self,func,var):
for v in func.variable_list:
if v.name == var:
return v
return -1
def is_func_declaration(self,line):
for func in self.function_list:
for l in func.declaration:
if l.line == line:
self.arduino_current_func = func
return True
return False
def find_function(self,name):
for func in self.function_list:
if func.name == name:
return func
def find_line(self,line):
for l in self.source:
if l.line == line:
return l
else:
return 0
def turn(self,type):
global temp
value = 0
int_temp = [int(i) for i in temp]
if type == 'int':
value = int_temp[0] + 256*int_temp[1]
elif type == 'float' or type == 'double':
sum_ = 0
for i in range(len(int_temp)):
sum_ += 256**i*int_temp[i]
value = struct.unpack('!f', bytes.fromhex(hex(sum_)[2:]))[0]
temp = []
return value
if __name__ == "__main__":
port = 'COM3'
baud_rate = 9600
folder = "C:\\Users\\xingxing\\Documents\\Arduino\\test4"
file = "test4.ino"
debugerv2 = debuger(port=port,baud_rate=baud_rate,file=file,folder=folder)
#debugerv2.turn()
debugerv2.debug()
|
Arduino-debuger
|
/Arduino%20debuger-1.0.0.tar.zip/debugerv2/debugerv2.py
|
debugerv2.py
|
from copy import deepcopy
from commandhooker import Colored
from debuger import baudRate
b = Colored()
DEADBEEF = "DEADBEEF"
class one_line:
def __init__(self,content='',line=0) -> None:
#c is a string and l is the line where code is at
self.content = content
self.line = line
self.before_line = []
self.after_line = []
class variable:
def __init__(self,name='',type='',value=0,addr=0,line=0) -> None:
self.name = name
self.value = value
self.addr = addr
self.type = type
self.line = line
class array:
def __init__(self,length=0,name='',type='',value=[],addr=0,line=0) -> None:
self.length = length
self.name = name
self.type = type
self.addr = addr
self.value = value
self.line = line
class function:
def __init__(self,difination=[],name='',type=''):
self.name = name
self.type = type
self.difination = difination# where it begins and where it ends
self.declaration = []
self.variable_list = []
type_list = ['int','char','double','float','void','String']
number_list = [str(i) for i in range(10)]
alpha_list = [chr(i) for i in range(97,97+26)]+[chr(i) for i in range(65,65+26)]
function_list = [function(name="global",type='void')]
default_variable = variable()
default_array = array()
# 0 read the source
def read_source(path):
#read source code and return a list, an element is a line of code.
if path[-3:]!="ino":
raise Exception("ERROR! Only .ino file can be debugged.")
with open(path,'r') as file:
source = file.readlines()
result = []
for i in range(len(source)):
result.append(one_line(source[i],i+1))
return result
# 1 get rid of annotation/'\n'/ two ; in oneline
# make all '{' a single line
def is_empty(line):
content = line.content
valid_character = [chr(i) for i in range(97,97+26)]+[chr(i) for i in range(65,65+26)]\
+ ['+','-','*','/','{','}','(',')']
for c in valid_character:
if c in content:
return False
return True
def remove_annotation(source):
#remove empty line and notation.
temp = deepcopy(source)
result = []
for line in temp:
if((index:=line.content.find("//"))!=-1):
#there is // in this line
line.content = line.content[:index]
result.append(line)
temp = deepcopy(result)
temp = one_line_one_sentence(temp)
result = []
flag = 0 # flag==0 means this line is not in annotation
for line in temp:
line.content = line.content.strip()
if((index:=line.content.find("/*"))!=-1):
flag = 1
line.content = line.content[:index]
if((index:=line.content.find("*/"))!=-1):
flag = 0
line.content = line.content[index+2:]
if(flag == 1):
line.content = ''
result.append(line)
temp = []
for line in result:
if(is_empty(line)):
continue
else:
temp.append(line)
return temp
def one_line_one_sentence(source):
#prevent two ';'s in one line
#source is after annotation removing
result = []
for line in source:
if line.content.count(';') > 1:
line_list = line.content[:-1].split(';')
for l in line_list:
result.append(one_line(l+';',line.line))
else:
result.append(line)
return result
def handle_spacein_line(source):
is_in_string = 0
temp = deepcopy(source)
result = []
for line in temp:
new_line = ''
if line.content[0] == '#':
result.append(line)
continue
for index in range(len(line.content)):
c = line.content[index]
if ord(c) == 34:
is_in_string = 1-is_in_string
if is_in_string:
new_line += c
continue
if c == ' ':
a = line.content[index+1]
b = line.content[index-1]
if (a in number_list or a in alpha_list) and (b in number_list or b in alpha_list):
new_line += c
else:
pass
else:
new_line += c
result.append(one_line(content=new_line,line=line.line))
return result
def replace_macro(source):
macro_list = []
for line in source:
if (index:=line.content.find("#define"))!=-1:
temp = line.content[index+7:].split(' ')
macro = []
for c in temp:
if(c!=' ' and c!=''):
macro.append(c)
macro_list.append(macro)
for line in source:
if line.content.find('#')!=-1:
continue
for macro in macro_list:
if line.content.find(macro[0])!=-1:
line.content = line.content.replace(macro[0],macro[1])
#2 find function in this code/local scope in this code
# in a certain line, there is alpha/digit/()/{}/space
def find_function_definition(source):
scope = []
for line in source:
flag = 0
if line.content.find('"') != -1:
continue
else:
if " " in line.content and "(" in line.content:
type = line.content.split(' ')[0]
for c in type:
if not (c in number_list or c in alpha_list):
flag = 1
if flag:
continue
name = line.content[line.content.find(' ')+1:line.content.find('(')]
scope.append([line,0])
scope[-1][1] = find_end_scope(source,line)
function_list.append(function(name=name,type=type,difination=scope[-1]))
return scope
def find_function_declaration(source):
global function_list
for function in function_list:
for line in source:
if function.name in line.content:
function.declaration.append(line)
def find_end_scope(source,line):
# find '}' matched to '{' in line
flag = 0
for l in source[source.index(line)+1:]:
flag = flag - l.content.count('{') + l.content.count('}')
if flag>0:
return l
# 3 find variable in one function/or in global
def find_variable_inoneline(temp_line):
line = deepcopy(temp_line)
flag = 0
variable_list = []
for type in type_list:
if (index:=line.content.find(type)) != -1:
#here comes a type in this line
if(index == 0):
# take int as example
# index=0 means 'int' is the first word in the sentense.
flag = 1
else:
if(line.content[index+len(type)]!=' '):
continue
for c in line.content[index+len(type):]:
if c == ' ':
continue
elif c == ')':
flag = 0
break
else:
flag = 1
break
# flag = 0: 'int' just a part of other expression.
# just like: 'void breakpoint()'. it has 'int' in this line but it's not used in variable declaration.
if(flag):
name = []
line.content = line.content[index+len(type)+1:].replace(' ','')
for i in range(len(line.content)):
if line.content[i] not in ['=',';']:
continue
else:
is_in = 0
start = 0
for i in range(len(line.content)):
c = line.content[i]
if c == '{':
is_in = 1
elif c == '}':
is_in = 0
elif c == ',' or c == ';':
if is_in:
continue
else:
name.append(line.content[start:i])
start = i+1
break
for n in name:
index1 = n.find('=')
if index1 == -1:
temp_name = n
else:
temp_name = n[:index1]
if (index1:=temp_name.find('[')) != -1:
#it means this variable is a array
index2 = n.find(']')
if index1+1==index2:
#int a[] = {1,2,3,4}
index1 = n.find('{')
index2 = n.find('}')
length = n[index1+1:index2].count(',')+1
n = n[:n.find('[')]
else:
#int a[5]
index2 = n.find(']')
length = int(n[index1+1:index2])
n = n[:index1]
variable_list.append(array(length=length,name=n,type=type,line=line))
else:
# an ordinary variable
variable_list.append(variable(name=temp_name,type=type,line=temp_line));
break
return variable_list
def find_variable_function(function,source):
for line in source:
if line.line > function.difination[0].line and \
line.line < function.difination[1].line:
function.variable_list += find_variable_inoneline(line)
def is_global_line(line):
for function in function_list[1:]:
if line.line > function.difination[0].line \
and line.line < function.difination[1].line:
return False
return True
def find_variable_global(source):
for line in source:
if is_global_line(line):
# print(line.content)
function_list[0].variable_list += find_variable_inoneline(line)
# 4 change the source file according to the function list and variable_list
def add_source(source):
# add "Serial.print((unsigned long) &variable)" after every variable
# add function name at begin of any function
for function in function_list[1:]:
# for local variable, print address after its difination
find_line(source,function.difination[0]).after_line.append(
"spl("+chr(34)+"DEADBEEFfunc"+chr(34)+");spl("+chr(34)+function.name+chr(34)+");\n")
if function.name == 'setup':
set_up = function
for var in function.variable_list:
if type(var) == type(default_array):
# if var is a array
find_line(source,var.line).after_line.append(
"spl("+chr(34)+"DEADBEEF"+chr(34)+");spl((unsigned long) &"+var.name+"[0]);\n")
else:
# then var is a variable
find_line(source,var.line).after_line.append(
"spl("+chr(34)+"DEADBEEF"+chr(34)+");spl((unsigned long) &"+var.name+");\n")
set_up.difination[0].after_line.insert(0,"Serial.begin("+str(baudRate)+");\n")
for var in function_list[0].variable_list:
# for global variable, print address at last of void setup()
set_up.difination[0].before_line.append(var.line.content+'\n')
# move all the global variables before setup function.
if type(var) == type(default_array):
# if var is a array
find_line(source,set_up.difination[1]).before_line.append(
"spl("+chr(34)+"DEADBEEF"+chr(34)+");spl((unsigned long) &"+var.name+"[0]);\n")
else:
# then var is a variable
find_line(source,set_up.difination[1]).before_line.append(
"spl("+chr(34)+"DEADBEEF"+chr(34)+");spl((unsigned long) &"+var.name+");\n")
#add breakpoint() after every line
for line in source:
if(is_global_line(line)):
continue
else:
line.before_line.append("breakpoint(" + str(line.line)+");\n")
def find_line(source,certain_line):
for line in source:
if line.line == certain_line.line:
return line
# 5 generate the new source
def generate(source,path):
source = get(source)
file = open(path,'w')
file.truncate(0)
file.write(' #include "debuger.hpp" \n')
for line in source:
file.write(line)
file.close()
def get(source):
# global variables have been in the before lines of "void setup"
# so if the line is a global variables, we just jump over it.
result = []
for line in source:
flag = 0
if line.content.find("Serial.begin")!=-1:
continue
for v in function_list[0].variable_list:
if line.line == v.line.line:
flag = 1
break
if flag:
continue
result += list(set(line.before_line))
# print(line.before_line)
result.append(line.content+'\n')
result += line.after_line
# print(line.after_line)
return result
def get_simple(source):
result = []
for line in source:
result.append(line.content)
return result
# 6 display the result
def show_function_variable(function):
for v in function.variable_list:
content = "In function "+ b.magenta(function.name)\
+ ', debuger finds ' + b.white_green(v.name)\
+ ' at line ' + str(v.line.line)
print(content)
def show():
for v in function_list[0].variable_list:
content = "In global "+ b.magenta(function_list[0].name)\
+ ', debuger finds ' + b.white_green(v.name)\
+ ' at line ' + str(v.line.line)
print(content)
for func in function_list[1:]:
content = "debuger finds function " + b.magenta(func.name)\
+ " from line " + str(func.difination[0].line) + " to line " + str(func.difination[1].line)
print(content)
show_function_variable(func)
# 7 get it all.
def interpret(source_path,new_source_path):
# source_path = new_source_path
source = read_source(source_path)
source_without_annatation = remove_annotation(source)
source = handle_spacein_line(source_without_annatation)
replace_macro(source)
fix_bug1(source,new_source_path)
find_function_definition(source)
find_function_declaration(source)
for function in function_list[1:]:
find_variable_function(function,source)
find_variable_global(source)
# for func in function_list:
# get_function_variable(func)
add_source(source)
generate(source,new_source_path)
show()
return function_list
# bug fixing
def fix_bug1(source,new_source_path):
# must make sure every end line of a function is a single '}'
# {
# ....
# } this is alright
#
# {
# .....; } this is what I want to remove.
for line in source:
if (index:= line.content.find(";}"))!=-1:
if(index == len(line.content)-2):
# then ';}' is at end of a line
line.content = line.content[:-1]
source.insert(source.index(line)+1,one_line('}',line.line))
else:
raise Exception(";} must at end of a line")
generate(source,new_source_path)
source = read_source(new_source_path)
return source
if __name__ == "__main__":
interpret('test/test.ino','test/debugertest.ino')
|
Arduino-debuger
|
/Arduino%20debuger-1.0.0.tar.zip/debugerv2/interpreter.py
|
interpreter.py
|
import os
import time
import numpy as np
def generate_pseudorandom_firmware():
aa = np.uint64(int(str(time.time()).replace(".", ""))).tobytes()
ba = bytearray(
reversed(np.uint64(int(str(time.time()).replace(".", ""))).tobytes())
)
r = np.random.bytes(8)
for i in range(len(ba)):
if ba[i] == 0:
ba[i] = r[i]
else:
break
return np.frombuffer(ba, dtype=np.uint64)[0]
def create_board(path, name, superboard="ArduinoBasicBoard"):
camelcase = "".join(x for x in name.title() if not x.isspace())
snakename = name.lower().replace(" ", "_")
os.makedirs(os.path.join(path, snakename), exist_ok=True)
firmware = generate_pseudorandom_firmware()
if os.path.exists(os.path.join(path, snakename, "board.py")):
raise ValueError(
name + "already exists as board: " + str(os.path.join(path, snakename))
)
with open(os.path.join(path, snakename, "board.py"), "w+") as f:
code = ""
code += "from ArduinoCodeCreator.arduino import *\n"
code += "from ArduinoCodeCreator.arduino_data_types import *\n"
code += "from ArduinoCodeCreator.basic_types import *\n"
code += "from ArduinoCodeCreator.statements import *\n"
code += "from arduino_controller.arduino_variable import arduio_variable\n"
code += "from arduino_controller.basicboard.board import ArduinoBoardModule, BasicBoardModule, ArduinoBoard\n"
code += "from arduino_controller.python_variable import python_variable\n"
code += "\n"
code += "\n"
code += "class {}Module(ArduinoBoardModule):\n".format(camelcase)
code += "\t# depencies\n" #
code += "\tbasic_board_module = BasicBoardModule\n"
code += "\n"
code += "\t# python_variables\n"
code += "\n"
code += "\t# arduino_variables\n"
code += "\n"
code += "\tdef instance_arduino_code(self, ad):\n"
code += "\t\tad.loop.add_call()\n"
code += "\t\tad.setup.add_call()\n"
code += "\t\tself.basic_board_module.dataloop.add_call()\n"
code += "\n"
code += "\n"
code += "class {}Board(ArduinoBoard):\n".format(camelcase)
code += "\tFIRMWARE = {}\n".format(firmware)
code += "\tmodules = [{}Module]\n".format(camelcase)
code += "\n"
code += "\n"
code += "if __name__ == '__main__':\n"
code += "\tins = {}Board()\n".format(camelcase)
code += "\tins.create_ino()"
f.write(code.replace("\t", " "))
if __name__ == "__main__":
create_board(
path=os.path.join(os.path.dirname(__file__), "boards", "test"),
name="autocreated " + str(int(time.time())),
)
|
ArduinoBoardCollection
|
/ArduinoBoardCollection-0.1.1566386412.tar.gz/ArduinoBoardCollection-0.1.1566386412/arduino_board_collection/create_board.py
|
create_board.py
|
from ArduinoCodeCreator.arduino import Arduino
from ArduinoCodeCreator.basic_types import Variable
from ArduinoCodeCreator.statements import if_, else_, elseif_
from arduino_controller.basicboard.board import (
ArduinoBoardModule,
ArduinoBoard,
BasicBoardModule,
)
from ArduinoCodeCreator.arduino_data_types import *
from arduino_controller.arduino_variable import arduio_variable
class DutyCycleBoardModule(ArduinoBoardModule):
basic_board_module = BasicBoardModule
signal_pin = arduio_variable(
name="signal_pin", arduino_data_type=uint8_t, eeprom=True
)
full_cycle = arduio_variable(
name="full_cycle", arduino_data_type=uint32_t, eeprom=True
)
duty_cycle = arduio_variable(
name="duty_cycle",
arduino_data_type=float_,
minimum=0,
maximum=100,
html_attributes={"step": 0.1},
save=False,
)
last_cycle = Variable("last_cycle", uint32_t, 0)
cycletime = Variable("cycletime", uint32_t, 0)
def instance_arduino_code(self, ad):
ad.setup.add_call(Arduino.pinMode(self.signal_pin, Arduino.OUTPUT))
ad.loop.add_call(
self.cycletime.set(self.basic_board_module.current_time - self.last_cycle),
if_(
self.cycletime > self.full_cycle,
(
self.cycletime.set(0),
self.last_cycle.set(self.basic_board_module.current_time),
),
),
if_(
self.duty_cycle == 0,
Arduino.digitalWrite(self.signal_pin, Arduino.HIGH),
),
elseif_(
self.duty_cycle == 100,
Arduino.digitalWrite(self.signal_pin, Arduino.LOW),
),
elseif_(
self.cycletime
< self.full_cycle
* ((self.duty_cycle.cast(float_) / self.duty_cycle.maximum)),
Arduino.digitalWrite(self.signal_pin, Arduino.LOW),
),
else_(Arduino.digitalWrite(self.signal_pin, Arduino.HIGH)),
)
self.signal_pin.arduino_setter.add_call(
Arduino.pinMode(self.signal_pin, Arduino.OUTPUT)
)
class DutyCycleBoard(ArduinoBoard):
FIRMWARE = 15657152897648263
modules = [DutyCycleBoardModule]
if __name__ == "__main__":
ins = DutyCycleBoard()
ins.create_ino()
|
ArduinoBoardCollection
|
/ArduinoBoardCollection-0.1.1566386412.tar.gz/ArduinoBoardCollection-0.1.1566386412/arduino_board_collection/boards/signal_boards/pulses/dutycycle_digital/board.py
|
board.py
|
from ArduinoCodeCreator.arduino import Arduino, Eeprom
from ArduinoCodeCreator.arduino_data_types import *
from ArduinoCodeCreator import basic_types as at
from ArduinoCodeCreator.basic_types import Include
from ArduinoCodeCreator.statements import for_, if_, else_, return_
from arduino_controller.basicboard.board import (
ArduinoBoardModule,
BasicBoardModule,
ArduinoBoard,
)
from arduino_controller.arduino_variable import arduio_variable
class SPI(at.ArduinoClass):
class_name = "SPI"
include = "<SPI.h>"
begin = at.Function("begin")
transfer = at.Function("transfer", uint8_t, uint8_t)
transfer16 = at.Function("transfer16", uint16_t, uint16_t)
transferbuff = at.Function(
"transfer", ((uint8_t_pointer, "buff"), (uint8_t, "size"))
)
class SerialPeripheralInterfaceModule(ArduinoBoardModule):
# depencies
basic_board_module = BasicBoardModule
unique = True
# arduino_variables
# sck = arduio_variable(name="sck", arduino_data_type=uint8_t, eeprom=True,default=13)
# miso = arduio_variable(name="miso", arduino_data_type=uint8_t, eeprom=True,default=12)
# mosi = arduio_variable(name="mosi", arduino_data_type=uint8_t, eeprom=True,default=11)
spi = SPI()
active_cs_pin = at.Variable(name="activate_cs_pin", type=uint8_t)
deactivate_pin = at.Function("deactivate_pin")
activate_pin = at.Function("activate_pin", uint8_t)
read16 = at.Function("read16", uint8_t, uint16_t)
@classmethod
def module_arduino_code(cls, board, arduino_code_creator):
cls.deactivate_pin.add_call(
if_(
cls.active_cs_pin > 0,
code=(
Arduino.digitalWrite(cls.active_cs_pin, Arduino.HIGH),
cls.active_cs_pin.set(0),
),
)
)
cls.activate_pin.add_call(
if_(cls.active_cs_pin == cls.activate_pin.arg1, return_()),
if_(cls.active_cs_pin > 0, cls.deactivate_pin()),
Arduino.pinMode(cls.activate_pin.arg1, Arduino.OUTPUT),
cls.active_cs_pin.set(cls.activate_pin.arg1),
Arduino.digitalWrite(cls.active_cs_pin, Arduino.LOW),
)
def instance_arduino_code(self, arduino_code_creator):
arduino_code_creator.setup.prepend_call(self.spi.begin())
self.read16.add_call(
self.activate_pin(self.read16.arg1),
self.basic_board_module.dummy16.set(self.spi.transfer16(0)),
self.deactivate_pin(),
return_(self.basic_board_module.dummy16),
)
|
ArduinoBoardCollection
|
/ArduinoBoardCollection-0.1.1566386412.tar.gz/ArduinoBoardCollection-0.1.1566386412/arduino_board_collection/boards/sensor_boards/basic/serial_peripheral_interface/board.py
|
board.py
|
from ArduinoCodeCreator import basic_types as at
from ArduinoCodeCreator.arduino import Arduino
from ArduinoCodeCreator.arduino_data_types import *
from ArduinoCodeCreator.basic_types import Variable
from ArduinoCodeCreator.statements import for_
from arduino_controller.basicboard.board import (
ArduinoBoardModule,
BasicBoardModule,
ArduinoBoard,
)
from arduino_controller.arduino_variable import arduio_variable
class HX711(at.ArduinoClass):
class_name = "HX711"
gains = at.ArduinoEnum(
"MotorInterfaceType",
{
128: ("128", "channel A, gain factor 128"),
64: ("64", "channel A, gain factor 64"),
32: ("32", "channel B, gain factor 32"),
},
)
begin = at.Function("begin", [uint8_t, uint8_t, uint8_t])
is_ready = at.Function("is_ready", return_type=bool_)
wait_ready = at.Function("wait_ready", uint32_t)
wait_ready_retry = at.Function(
"wait_ready_retry", [uint16_t, uint32_t], return_type=bool_
)
wait_ready_timeout = at.Function(
"wait_ready_timeout", [uint16_t, uint32_t], return_type=bool_
)
set_gain = at.Function("set_gain", uint8_t)
read = at.Function("read", return_type=long_)
read_average = at.Function("read_average", uint8_t, return_type=long_)
get_value = at.Function("get_value", uint8_t, return_type=double_)
get_units = at.Function("get_units", uint8_t, return_type=float_)
tare = at.Function("tare", uint8_t)
set_scale = at.Function("set_scale", float_)
get_scale = at.Function("get_scale", return_type=float_)
set_offset = at.Function("set_offset", long_)
get_offset = at.Function("get_offset", return_type=long_)
power_down = at.Function("power_down")
power_up = at.Function("power_up")
include = "<HX711.h>"
#https://github.com/EdwinCroissantArduinoLibraries/SimpleHX711
#([^\s]*) ([^\s]*)\((.*)\); with $2 = at.Function("$2",$3,return_type=$1)
# ,, with ,
#,return_type=void with
class HX711Module(ArduinoBoardModule):
# depencies
basic_board_module = BasicBoardModule
#sets minimum datarate
basic_board_module.data_rate.minimum = max(basic_board_module.data_rate.minimum,180)
# arduino_variables
hx711 = HX711()
hx711_scale = hx711("hx711_scale")
doutPin = arduio_variable(
name="doutPin", arduino_data_type=uint8_t, eeprom=True, default=2
)
sckPin = arduio_variable(
name="sckPin", arduino_data_type=uint8_t, eeprom=True, default=3
)
gain = arduio_variable(
name="gain",
arduino_data_type=uint8_t,
eeprom=True,
allowed_values=HX711.gains.possibilities,
)
scale = arduio_variable(
name="scale",
arduino_data_type=float_,
eeprom=True,
html_attributes={"step": 0.1},
)
offset = arduio_variable(name="offset", arduino_data_type=long_, eeprom=True)
nread = arduio_variable(name="nread", arduino_data_type=uint8_t, eeprom=True)
value = arduio_variable(
name="value",
arduino_data_type=float_,
arduino_setter=None,
is_data_point=True,
changeable=False,
save=False,
)
reinitalize_hx711 = at.Function("reinitalize_hx711")
def instance_arduino_code(self, ad):
self.reinitalize_hx711.add_call(
self.hx711_scale.power_down(),
self.hx711_scale.begin(self.doutPin, self.sckPin, self.gain),
self.hx711_scale.wait_ready_timeout(1000, 0),
self.hx711_scale.set_scale(self.scale),
self.hx711_scale.set_offset(self.offset),
)
self.doutPin.arduino_setter.add_call(self.reinitalize_hx711())
self.sckPin.arduino_setter.add_call(self.reinitalize_hx711())
self.gain.arduino_setter.add_call(self.hx711_scale.set_gain(self.gain))
self.scale.arduino_setter.add_call(self.hx711_scale.set_scale(self.scale))
self.scale.arduino_getter.prepend_call(
self.scale.set(self.hx711_scale.get_scale())
)
self.offset.arduino_setter.add_call(self.hx711_scale.set_offset(self.offset))
self.offset.arduino_getter.prepend_call(
self.offset.set(self.hx711_scale.get_offset())
)
ad.setup.add_call(self.reinitalize_hx711())
self.basic_board_module.dataloop.prepend_call(
self.value.set(self.hx711_scale.get_units(self.nread))
)
class HX711Board(ArduinoBoard):
FIRMWARE = 1712005307122661283
modules = [HX711Module]
if __name__ == "__main__":
ins = HX711Board()
print("AA")
ins.create_ino()
|
ArduinoBoardCollection
|
/ArduinoBoardCollection-0.1.1566386412.tar.gz/ArduinoBoardCollection-0.1.1566386412/arduino_board_collection/boards/sensor_boards/basic/hx711_board/board.py
|
board.py
|
from functools import partial
from ArduinoCodeCreator.arduino import Arduino
from ArduinoCodeCreator.arduino_data_types import *
from arduino_board_collection.boards.sensor_boards.basic.analog_read_board.board import (
AnalogReadModule,
)
from arduino_controller.basicboard.board import ArduinoBoardModule, ArduinoBoard
from arduino_controller.arduino_variable import arduio_variable
from arduino_controller.python_variable import python_variable
class ThermistorBoardModule(ArduinoBoardModule):
analog_read_module = AnalogReadModule
# analog_read_module.analog_value.is_data_point = False
# arduino_variables
thermistor_base_resistance = arduio_variable(
name="thermistor_base_resistance",
arduino_data_type=uint32_t,
eeprom=True,
default=10 ** 5,
)
reference_resistance = arduio_variable(
name="reference_resistance",
arduino_data_type=uint32_t,
eeprom=True,
default=10 ** 5,
)
# python_variables
temperature = python_variable(
"temperature", type=np.float, changeable=False, is_data_point=True, save=False
)
reference_temperature = python_variable(
"reference_temperature", type=np.float, default=298.15, minimum=0
)
b = python_variable("b", type=np.uint32, default=4000)
# a = python_variable("a", type=np.float,default=1.009249522)
# b = python_variable("b", type=np.float,default=2.378405444)
# c = python_variable("c", type=np.float,default=2.019202697)
@classmethod
def module_arduino_code(cls, board, arduino_code_creator):
arduino_code_creator.setup.add_call(Arduino.analogReference(Arduino.EXTERNAL))
def post_initalization(self):
self.analog_read_module.analog_value.data_point_modification(
self.resistance_to_temperature
)
def resistance_to_temperature(self, data):
try:
R2 = self.reference_resistance * data / (1023.0 - data)
Tk = R2 / self.thermistor_base_resistance
Tk = np.log(Tk)
Tk /= self.b
Tk += 1 / self.reference_temperature
Tk = 1 / Tk
self.temperature = Tk
except ZeroDivisionError:
pass
return data
# try:
# R2 = self.reference_resistance*data/ (1023.0-data)
# print(R2)
# logR2 = np.log(R2)
# Tk = (1.0 / (self.a/10**3 + self.b*logR2/10**4 + self.c*logR2*logR2*logR2/10**7))
# self.temperature = Tk
# except ZeroDivisionError:
# pass
class ThermistorBoard(ArduinoBoard):
FIRMWARE = 15650180050147572
modules = [ThermistorBoardModule]
class DualThermistorBoard(ArduinoBoard):
FIRMWARE = 15650180050147573
modules = [ThermistorBoardModule, ThermistorBoardModule]
if __name__ == "__main__":
ins = DualThermistorBoard()
ins.create_ino()
|
ArduinoBoardCollection
|
/ArduinoBoardCollection-0.1.1566386412.tar.gz/ArduinoBoardCollection-0.1.1566386412/arduino_board_collection/boards/sensor_boards/thermal/thermistor/board.py
|
board.py
|
import time
from functools import partial
from ArduinoCodeCreator.arduino_data_types import *
from arduino_board_collection.boards.sensor_boards.thermal.thermistor.board import (
ThermistorBoardModule,
)
from arduino_board_collection.boards.signal_boards.switches.relay.board import (
RelayBoardModule,
)
from arduino_controller.basicboard.board import ArduinoBoard, ArduinoBoardModule
from arduino_controller.python_variable import python_variable
try:
_current_time = time.monotonic
except AttributeError:
_current_time = time.time
class RelayThermistorModule(ArduinoBoardModule):
thermistor = ThermistorBoardModule
relay = RelayBoardModule
target_temperature = python_variable(
"target_temperature", type=np.float, default=298.15
)
max_temperature = python_variable(
"max_temperature", type=np.float, default=300, minimum=0
)
min_temperature = python_variable("min_temperature", type=np.float)
max_on_time = 100
min_on_time = 0
threshold = python_variable(
"threshold", type=np.float, default=50, minimum=0, maximum=100
)
running = python_variable("running", type=np.bool, default=False, save=False)
kp = python_variable("kp", type=np.float, default=1)
ki = python_variable("ki", type=np.float)
kd = python_variable("kd", type=np.float)
def post_initalization(self):
self.thermistor.temperature.setter = self.pdi_temperature
self._last_time = _current_time()
self._last_input = None
self._integral = 0
def pdi_temperature(self, var, instance, data):
kelvin = var.default_setter(var=var, instance=instance, data=data)
target = self.target_temperature
print("kelvin", kelvin, "target", target)
if self.running:
on_time = self.pid(data, target)
if on_time is not None:
if on_time > self.threshold:
self.relay.active = False
else:
self.relay.active = True
else:
self.reset()
def reset(self):
self._last_time = _current_time()
self._last_input = None
self._integral = 0
def pid(self, input, target):
if self._last_input is None:
self._last_time = _current_time()
time.sleep(0.01)
now = _current_time()
if now - self._last_time:
dt = now - self._last_time
else:
return None
error = target - input
d_input = input - (self._last_input if self._last_input is not None else input)
# compute integral and derivative terms
proportional = self.kp * error
self._integral += self.ki * error * dt
self._integral = min(
self.max_on_time, max(self.min_on_time, self._integral)
) # avoid integral windup
derivative = -self.kd * d_input / dt
# compute final output
output = proportional + self._integral + derivative
output = min(self.max_on_time, max(self.min_on_time, output))
self._last_input = input
self._last_time = now
return output
class RelayThermistor2Board(ArduinoBoard):
FIRMWARE = 15650261815701852
modules = [RelayThermistorModule, ThermistorBoardModule]
if __name__ == "__main__":
ins = RelayThermistor2Board()
ins.create_ino()
|
ArduinoBoardCollection
|
/ArduinoBoardCollection-0.1.1566386412.tar.gz/ArduinoBoardCollection-0.1.1566386412/arduino_board_collection/boards/sensor_signal_boards/signal_switch_boards/relay_thermistor_pid/board.py
|
board.py
|
from ArduinoCodeCreator.arduino_data_types import *
from arduino_board_collection.boards.controller_boards.basic.pid.board import PIDModule
from arduino_board_collection.boards.sensor_boards.thermal.thermistor.board import (
ThermistorBoardModule,
)
from arduino_board_collection.boards.signal_boards.pulses.dutycycle_digital.board import (
DutyCycleBoardModule,
)
from arduino_controller.basicboard.board import ArduinoBoard, ArduinoBoardModule
from arduino_controller.python_variable import python_variable
class RelayThermistorBangBangModule(ArduinoBoardModule):
thermistor = ThermistorBoardModule
relay = DutyCycleBoardModule
pid = PIDModule
target_temperature = python_variable(
"target_temperature", type=np.float, default=298.15
)
max_temperature = python_variable(
"max_temperature", type=np.float, default=300, minimum=0
)
min_temperature = python_variable("min_temperature", type=np.float)
running = python_variable("running", type=np.bool, default=False, save=False)
def post_initalization(self):
self.thermistor.temperature.data_point_modification(self.bang_bang_temperature)
self.relay.duty_cycle.is_data_point = True
self.relay.duty_cycle.changeable = False
self.pid.minimum = self.relay.duty_cycle.minimum
self.pid.maximum = self.relay.duty_cycle.maximum
def bang_bang_temperature(self, data):
self.pid.current = data
self.pid.target = self.target_temperature
if self.running:
pid = self.pid.pid()
if pid is None:
pid = 0
self.relay.duty_cycle = pid
else:
self.pid.reset()
self.relay.duty_cycle = 0
return data
class Relay2ThermistorBangBangBoard(ArduinoBoard):
FIRMWARE = 15657144496468015
modules = [RelayThermistorBangBangModule, ThermistorBoardModule]
if __name__ == "__main__":
ins = Relay2ThermistorBangBangBoard()
ins.create_ino()
|
ArduinoBoardCollection
|
/ArduinoBoardCollection-0.1.1566386412.tar.gz/ArduinoBoardCollection-0.1.1566386412/arduino_board_collection/boards/sensor_signal_boards/signal_switch_boards/relay_thermistor_bang_bang/board.py
|
board.py
|
from ArduinoCodeCreator import basic_types as at
from ArduinoCodeCreator.arduino import Arduino
from ArduinoCodeCreator.arduino_data_types import *
from ArduinoCodeCreator.statements import while_
from arduino_controller.arduino_variable import arduio_variable
from arduino_controller.basicboard.board import (
ArduinoBoardModule,
ArduinoBoard,
BasicBoardModule,
)
class AccelStepper(at.ArduinoClass):
class_name = "AccelStepper"
motor_interface_type = at.ArduinoEnum(
"MotorInterfaceType",
{
0: (
"FUNCTION",
"Use the functional interface, implementing your own driver functions (internal use only)",
),
1: ("DRIVER", "Stepper Driver, 2 driver pins required"),
2: ("FULL2WIRE", "2 wire stepper, 2 motor pins required"),
3: (
"FULL3WIRE",
"3 wire stepper, such as HDD spindle, 3 motor pins required",
),
4: ("FULL4WIRE", "4 wire full stepper, 4 motor pins required"),
6: (
"HALF3WIRE",
"3 wire half stepper, such as HDD spindle, 3 motor pins required",
),
8: ("HALF4WIRE", "4 wire half stepper, 4 motor pins required)"),
},
)
# void moveTo(long absolute);
moveTo = at.Function("moveTo", long_)
# void move(long relative);
run = at.Function("run", return_type=bool_)
# runSpeed = at.Function("runSpeed",return_type=bool_)
setMaxSpeed = at.Function("setMaxSpeed", float_)
# float maxSpeed ()
setAcceleration = at.Function("setAcceleration", float_)
# void setSpeed(float speed);
# float speed();
# long distanceToGo();
# long targetPosition();
currentPosition = at.Function("currentPosition", return_type=long_)
setCurrentPosition = at.Function("setCurrentPosition", long_)
# void runToPosition();
# boolean runSpeedToPosition();
# void runToNewPosition(long position);
stop = at.Function("stop")
# void setMinPulseWidth (unsigned int minWidth)
setEnablePin = at.Function("setEnablePin", long_)
# void setPinsInverted (bool directionInvert=false, bool stepInvert=false, bool enableInvert=false)
# void setPinsInverted (bool pin1Invert, bool pin2Invert, bool pin3Invert, bool pin4Invert, bool enableInvert)
# bool isRunning ()
disableOutputs = at.Function("disableOutputs")
enableOutputs = at.Function("enableOutputs")
include = "<AccelStepper.h>"
class AccelStepperBoardModule(ArduinoBoardModule):
# depencies
basic_board_module = BasicBoardModule
accel_stepper = AccelStepper()
stepPin = arduio_variable(
name="stepPin", arduino_data_type=uint8_t, eeprom=True, default=2
)
dirPin = arduio_variable(
name="dirPin", arduino_data_type=uint8_t, eeprom=True, default=3
)
enablePin = arduio_variable(
name="enablePin", arduino_data_type=uint8_t, eeprom=True, default=4
)
stepper = accel_stepper("stepper")
reinitalize_stepper = at.Function("reinitalize_stepper")
max_steps_per_loop = arduio_variable(
name="max_steps_per_loop",
arduino_data_type=uint8_t,
eeprom=True,
default=1,
minimum=1,
)
steps_per_mm = arduio_variable(
"steps_per_mm", uint16_t, eeprom=True, default=200, minimum=1
)
# step_per_mm_dependend
stepper_max_speed = arduio_variable(
name="stepper_max_speed",
arduino_data_type=float_,
eeprom=True,
default=1000,
minimum=0.01,
html_attributes={"step": 0.01},
)
stepper_acceleration = arduio_variable(
name="stepper_acceleration",
arduino_data_type=float_,
eeprom=True,
default=10,
minimum=0.01,
html_attributes={"step": 0.01},
)
target_position = arduio_variable(
name="target_position",
arduino_data_type=float_,
save=False,
html_attributes={"step": 0.1},
)
stepper_current_position = arduio_variable(
name="stepper_current_position",
arduino_data_type=float_,
default=0,
save=True,
is_data_point=True,
html_attributes={"step": 0.1},
)
def instance_arduino_code(self, ad):
self.stepper = self.accel_stepper(
"stepper",
AccelStepper.motor_interface_type["DRIVER"],
self.stepPin,
self.dirPin,
)
self.reinitalize_stepper.add_call(
self.stepper.stop(),
while_(self.stepper.run()),
self.stepper.disableOutputs(),
self.stepper.reinitalize(),
self.stepper.setMaxSpeed(self.stepper_max_speed * self.steps_per_mm),
self.stepper.setCurrentPosition(
self.stepper_current_position * self.steps_per_mm
),
self.stepper.setAcceleration(self.stepper_acceleration * self.steps_per_mm),
self.stepper.setEnablePin(self.enablePin),
)
self.stepPin.arduino_setter.add_call(self.reinitalize_stepper())
self.dirPin.arduino_setter.add_call(self.reinitalize_stepper())
self.enablePin.arduino_setter.add_call(
self.stepper.setEnablePin(self.enablePin)
)
ad.setup.add_call(self.reinitalize_stepper())
self.stepper_current_position.arduino_setter.add_call(
self.stepper.setCurrentPosition(
self.stepper_current_position * self.steps_per_mm
)
)
self.stepper_current_position.arduino_getter.prepend_call(
self.stepper_current_position.set(
self.stepper.currentPosition() / self.steps_per_mm.cast(float_)
)
)
self.stepper_max_speed.arduino_setter.add_call(
self.stepper.setMaxSpeed(self.stepper_max_speed * self.steps_per_mm)
)
self.stepper_acceleration.arduino_setter.add_call(
self.stepper.setAcceleration(self.stepper_acceleration * self.steps_per_mm)
)
self.target_position.arduino_setter.add_call(
self.stepper.moveTo(self.target_position * self.steps_per_mm)
)
steps_in_loop = ad.add(at.Variable(name="steps_in_loop", type=uint8_t, value=0))
ad.loop.add_call(
steps_in_loop.set(0),
while_(
(steps_in_loop.increment() < self.max_steps_per_loop).and_(
self.stepper.run()
)
),
)
self.basic_board_module.dataloop.prepend_call(
self.stepper_current_position.set(
self.stepper.currentPosition() / self.steps_per_mm.cast(float_)
)
)
def post_initalization(self):
for var in [
self.stepper_max_speed,
self.stepper_acceleration,
self.target_position,
self.stepper_current_position,
]:
# var.modulvar_getter_modification(self.step_to_mm)
# var.modulvar_setter_modification(self.mm_to_step)
# var.data_point_modification(self.step_to_mm)
pass
def mm_to_step(self, mm):
return mm * self.steps_per_mm
def step_to_mm(self, step):
return step / self.steps_per_mm
class AccelStepperBoard(ArduinoBoard):
FIRMWARE = 13264008974968030663
modules = [AccelStepperBoardModule]
if __name__ == "__main__":
ins = AccelStepperBoard()
ins.create_ino()
|
ArduinoBoardCollection
|
/ArduinoBoardCollection-0.1.1566386412.tar.gz/ArduinoBoardCollection-0.1.1566386412/arduino_board_collection/boards/controller_boards/motors/AccelStepperBoard/board.py
|
board.py
|
from ArduinoCodeCreator.arduino_data_types import *
from arduino_controller.basicboard.board import ArduinoBasicBoard
from arduino_controller.arduino_variable import arduio_variable
class SimplePulseBoard(ArduinoBasicBoard):
FIRMWARE = 15627604053828192
CLASSNAME = "Simple Pulse Board"
PULSE_TYPE_SQUARE = 0
PULSE_TYPE_SINE = 1
PULSEPIN = 6
pulse_type = arduio_variable(
name="pulse_type",
default=PULSE_TYPE_SINE,
maximum=1,
allowed_values={PULSE_TYPE_SQUARE: "square", PULSE_TYPE_SINE: "sine"},
eeprom=True,
)
pulse_pin = arduio_variable(
name="pulse_pin", arduino_data_type=uint8_t, eeprom=True
)
wavelength = arduio_variable(
name="wavelength", arduino_data_type=uint16_t, minimum=1, default=1000
) # in millisec
current_val = arduio_variable(
name="current_val", arduino_data_type=uint16_t, is_data_point=True, save=False
) # in mV
running = arduio_variable(name="pulsing", arduino_data_type=bool_)
def __init__(self):
super().__init__()
def get_frequency(self):
return 1000 / self.wavelength
def set_frequency(self, hertz):
self.wavelength = 1000 / hertz
frequency = property(get_frequency, set_frequency)
#
# class SimplePulseBoardArduinoData(ArduinoData):
#
# pulse_pos = ArduinoDataGlobalVariable("pulse_pos", ArduinoDataTypes.double, 0)
# max_current_val = ArduinoDataGlobalVariable("max_current_val", ArduinoDataTypes.uint16_t, -1)
#
# def __init__(self, board_instance):
# super().__init__(board_instance)
# self.loop_function = ArduinoLoopFunction(
# ArduinoDataFunction.if_condition(
# board_instance.get_module_var_by_name("running").name,
# self.pulse_pos.code_set(ArduinoDataFunction.divide(
# ArduinoDataFunction.mod(ArduinoBasicBoardArduinoData.ct,board_instance.get_module_var_by_name("wavelength").name),
# ArduinoDataFunction.multiply(float(1.0),board_instance.get_module_var_by_name("wavelength").name)
# ))+
# ArduinoDataFunction.if_condition(
# ArduinoDataFunction.equal(board_instance.get_module_var_by_name("pulse_type").name,board_instance.PULSE_TYPE_SQUARE),
# ArduinoDataFunction.if_condition(ArduinoDataFunction.lesser_equal_than(self.pulse_pos,0.5),
# ArduinoDataFunction.set_variable(board_instance.get_module_var_by_name("current_val").name,self.max_current_val)
# )+
# ArduinoDataFunction.else_condition(ArduinoDataFunction.set_variable(board_instance.get_module_var_by_name("current_val").name,0))
# )+
# ArduinoDataFunction.elseif_condition(
# ArduinoDataFunction.equal(board_instance.get_module_var_by_name("pulse_type").name,board_instance.PULSE_TYPE_SINE),
# ArduinoDataFunction.set_variable(board_instance.get_module_var_by_name("current_val").name,
# ArduinoDataFunction.multiply(self.max_current_val,
# ArduinoDataFunction.divide(
# ArduinoDataFunction.add(1,
# ArduinoDataFunction.sin(
# ArduinoDataFunction.multiply(2,self.pulse_pos,ArduinoDataFunction.PI())
# ))
# ,2)
# )
# )
# )+
# ArduinoDataFunction.analog_write(board_instance.PULSEPIN,
# ArduinoDataFunction.map(board_instance.get_module_var_by_name("current_val").name,0,self.max_current_val,0,255)
# )
# )
#
# )
if __name__ == "__main__":
ins = SimplePulseBoard()
ins.create_ino()
|
ArduinoBoardCollection
|
/ArduinoBoardCollection-0.1.1566386412.tar.gz/ArduinoBoardCollection-0.1.1566386412/arduino_board_collection_bu/boards/signal_boards/pulses/simple_pulse_board/board.py
|
board.py
|
import struct
import numpy as np
import scipy.interpolate
from ArduinoCodeCreator.arduino_data_types import (
uint32_t,
uint8_t,
boolean,
uint16_t,
float_,
)
from ArduinoCodeCreator.basic_types import ArduinoClass, Function, ArduinoEnum
from arduino_controller.arduino_variable import arduio_variable
from arduino_controller.basicboard.board import (
ArduinoBasicBoard,
COMMAND_FUNCTION_COMMUNICATION_ARGUMENTS,
WRITE_DATA_FUNCTION,
)
from arduino_controller.python_variable import python_variable
REL_IR_SENSITIVITY = np.array(
[
(301.5282884840381, 0.0003707002656236913),
(311.14929801103125, 0.00033747854764376584),
(320.77030753802444, 0.0003042568296638404),
(330.3913170650176, 0.0002710351116839149),
(340.0123265920107, 0.00023781339370398946),
(349.63333611900384, 0.00020459167572384196),
(359.254345645997, 0.0006843132833542764),
(368.8753551729901, 0.001420506553790002),
(378.4963646999833, 0.0013872848358100764),
(388.11737422697644, 0.001354063117830151),
(397.7383837539696, 0.0010643697370449345),
(407.3593932809627, 0.0012876196818703),
(416.9804028079559, 0.0012543979638903746),
(426.60141233494903, 0.0012211762459104492),
(436.22242186194217, 0.0011879545279305237),
(445.8434313889353, 0.0011547328099505982),
(455.4644409159285, 0.0011215110919704507),
(465.0854504429216, 0.0016012326996008852),
(474.70645996991476, 0.0033633126212573305),
(484.3274694969079, 0.006664222519745078),
(494.58987965903395, 0.011459002336731139),
(503.5694885508942, 0.016160508225522285),
(513.5111983954538, 0.024430975817301803),
(522.8115076048805, 0.030639671951514735),
(532.4325171318736, 0.041634731734158326),
(542.0535266588668, 0.054040385662230794),
(551.67453618586, 0.06683074708451109),
(560.8679452894312, 0.0804062484417174),
(569.4199537578695, 0.09448265948002144),
(578.6133628614407, 0.10751672066019469),
(588.2343723884339, 0.12094826123948788),
(597.8553819154271, 0.13296920767335263),
(607.4763914424202, 0.14422073911880162),
(616.6698005459914, 0.15544525023362699),
(625.0347338291826, 0.16980727576400867),
(631.2883900217282, 0.18741810846517937),
(637.0609957379241, 0.20294676999195693),
(641.0124817936535, 0.21811533182563037),
(645.9604295503927, 0.23428038700004528),
(651.7330352665887, 0.24815266903787248),
(657.7805269692701, 0.2618408078388966),
(665.2024486043791, 0.2745013672630695),
(672.8992562259735, 0.2887410261322251),
(680.5960638475681, 0.3002938390100879),
(688.2928714691626, 0.3159379855565101),
(695.7147931042716, 0.32857564572507536),
(701.7622848069531, 0.3428744313423022),
(707.5348905231489, 0.3563192606087875),
(713.3074962393448, 0.3695503634896018),
(719.0801019555407, 0.38299519275608707),
(725.5742833862611, 0.3943536981334316),
(733.7521414842053, 0.4021799043465579),
(744.644498698694, 0.41175997997103997),
(753.3950359351495, 0.418569008369016),
(763.9781464148421, 0.4275089726774203),
(772.9577553067023, 0.43512937034766097),
(781.857189119171, 0.4488198742186079),
(788.3513705498914, 0.46333084378459966),
(794.8455519806117, 0.4758648442831346),
(803.0234100785559, 0.48497340881028717),
(813.3659953200736, 0.49282419909471864),
(822.9870048470667, 0.4914231285084443),
(832.0582424010888, 0.4862013072366246),
(840.7324224190763, 0.47583106886985505),
(849.2844308875146, 0.4671812408984757),
(851.8500334280461, 0.4570417510928755),
(859.2719550631551, 0.44617103545467096),
(865.3194467658366, 0.4325021968898066),
(871.0920524820324, 0.41773514324771943),
(874.9404562928297, 0.40137178605669566),
(880.7130620090256, 0.38735277476445706),
(886.4856677252214, 0.37119649961550827),
(890.6547718535852, 0.35696929889059525),
(894.5031756643824, 0.34562851176284015),
(898.3515794751797, 0.3345014510207559),
(902.1999832859769, 0.32273321112165876),
(906.4973675413672, 0.31271597723822486),
(913.1496084143167, 0.2988801758107126),
(919.1971001169982, 0.2839900436134426),
(924.9697058331941, 0.2711465274423944),
(931.0171975358755, 0.2594317586893793),
(938.4391191709844, 0.24775040940266535),
(946.135926792579, 0.23570172283428747),
(953.8327344141735, 0.22317215189814976),
(961.529542035768, 0.21048228617275888),
(969.2263496573626, 0.19667035692259527),
(976.6482712924715, 0.18398144038914666),
(982.6957629951529, 0.1698546167121302),
(988.4683687113488, 0.15572874222705602),
(994.2409744275448, 0.14096168858496883),
(1000.0135801437406, 0.12833189879959161),
(1005.7861858599365, 0.11677074094256934),
(1011.5587915761324, 0.10478213031420525),
(1017.6062832788139, 0.092609376449038),
(1025.0282049139228, 0.08074483311746328),
(1032.7250125355172, 0.06949762049535158),
(1040.8494205805337, 0.0570912467633895),
(1049.4014290489722, 0.05100613542006238),
(1052.6084322246365, 0.041591100544544846),
(1060.7633831570402, 0.03786852794556306),
(1065.7571452448606, 0.029790746318067107),
(1074.2327964948306, 0.025548016534713502),
(1084.9991642988466, 0.019465436369898947),
(1094.2994735082734, 0.01661213375166093),
(1101.9962811298678, 0.012994953098004247),
]
)
REL_FULL_SENSITIVITY = np.array(
[
(365.9890523, 0.007842265),
(377.5342637, 0.007802399),
(385.2310714, 0.007775821),
(400.4322664, 0.007723331),
(412.169898, 0.008537706),
(423.4745842, 0.013254082),
(427.5635133, 0.024941483),
(431.8242461, 0.035826816),
(434.5731059, 0.047724937),
(438.1466238, 0.061085763),
(442.3157279, 0.074688791),
(443.9192295, 0.086309969),
(446.8055323, 0.096900831),
(449.6918352, 0.110141901),
(454.364897, 0.12624684),
(456.1058416, 0.138545362),
(458.7630728, 0.149680491),
(462.0617046, 0.162492684),
(463.1612485, 0.174726249),
(465.7268511, 0.185745672),
(467.0096523, 0.198564825),
(468.9338543, 0.210355878),
(470.8580562, 0.224839882),
(473.2098585, 0.243425957),
(475.2562319, 0.260272743),
(476.6306619, 0.280602536),
(474.70646, 0.270350314),
(478.5548638, 0.306243058),
(478.5548638, 0.29418889),
(480.4790657, 0.33188358),
(480.4790657, 0.31957294),
(482.8843181, 0.35816362),
(482.4032676, 0.34495699),
(484.3274695, 0.382431847),
(483.846419, 0.37162506),
(486.6792718, 0.409943543),
(486.2516714, 0.395725091),
(488.6569238, 0.433161648),
(486.2516714, 0.424193445),
(490.5811257, 0.457840401),
(488.1758733, 0.446414345),
(492.4518775, 0.485867719),
(491.0621762, 0.471624092),
(494.3760794, 0.507091229),
(490.1000752, 0.498556939),
(496.1475669, 0.531877373),
(496.3537314, 0.521617794),
(498.2244833, 0.556804946),
(495.8726809, 0.542992094),
(500.2708567, 0.573814571),
(502.7142877, 0.595117708),
(501.6452866, 0.583580174),
(503.8100138, 0.611357129),
(506.0434624, 0.626188135),
(507.9676643, 0.640837014),
(509.8918662, 0.654020341),
(511.5411822, 0.66958614),
(514.015156, 0.683683538),
(515.7561006, 0.697233886),
(517.0389019, 0.708770681),
(519.6045044, 0.7207305),
(521.5287063, 0.731623901),
(523.3612796, 0.745021271),
(527.5151123, 0.759601386),
(530.5083152, 0.774307639),
(535.456263, 0.787663719),
(539.1672238, 0.799100533),
(543.0156276, 0.80998729),
(546.8640314, 0.821087773),
(551.1247642, 0.832492156),
(554.1485101, 0.845122104),
(558.3023427, 0.85966151),
(561.5704317, 0.873674747),
(565.1439495, 0.887951543),
(570.4355048, 0.900619458),
(574.2151871, 0.912101833),
(579.5754638, 0.922708579),
(586.3101705, 0.932089284),
(595.93118, 0.936188106),
(602.6658867, 0.927544553),
(606.1019615, 0.915838802),
(608.7591927, 0.903372431),
(611.0040949, 0.89267836),
(615.1731991, 0.879626655),
(620.7533846, 0.86780969),
(629.1236629, 0.879578483),
(631.5289153, 0.895279067),
(627.6805114, 0.867401063),
(634.8428185, 0.914253651),
(630.5668143, 0.903297129),
(636.9808207, 0.928922147),
(638.9050226, 0.940243001),
(640.8292245, 0.952418761),
(642.7534264, 0.963739615),
(644.0362276, 0.974806212),
(650.450234, 0.989383951),
(660.7126442, 0.990179673),
(664.0479275, 0.981405374),
(668.0887515, 0.972201187),
(676.1062594, 0.962698299),
(685.8438872, 0.953701119),
(696.2645651, 0.951616694),
(699.5631969, 0.945926288),
(710.4211934, 0.953781405),
(721.0043039, 0.959088021),
(725.8148086, 0.95169785),
(731.5874143, 0.94173964),
(737.1194948, 0.928576365),
(740.2463229, 0.916767871),
(744.0947267, 0.907265131),
(748.6647063, 0.895355477),
(752.7536353, 0.884494744),
(756.4645961, 0.874284128),
(762.1341196, 0.861807356),
(766.2230486, 0.850465738),
(771.0335534, 0.842541251),
(779.692462, 0.838407805),
(789.7507901, 0.847955787),
(800.3776325, 0.851256138),
(806.7687316, 0.842417856),
(814.1906533, 0.830484615),
(815.6750376, 0.821099954),
(819.963259, 0.812145277),
(825.6327825, 0.799874599),
(828.7596106, 0.7882264),
(832.9287147, 0.777354703),
(835.0819883, 0.765561785),
(838.8616706, 0.752702251),
(843.0536819, 0.738787927),
(844.5380662, 0.728414019),
(848.0016296, 0.717672994),
(849.9258315, 0.706595323),
(853.2931849, 0.694946294),
(855.6984372, 0.682723526),
(858.5847401, 0.671899004),
(860.8296423, 0.66077748),
(862.7538442, 0.650084517),
(865.3194468, 0.64037248),
(868.7402502, 0.626482701),
(871.0920525, 0.613935965),
(873.9783553, 0.603239679),
(875.4902283, 0.591754299),
(878.1474595, 0.579715381),
(880.0716614, 0.568167512),
(882.6372639, 0.557472333),
(884.5614658, 0.547463294),
(886.4856677, 0.537454255),
(888.4098696, 0.527701687),
(890.3340715, 0.517692648),
(892.2582734, 0.506914194),
(894.1824753, 0.496648683),
(896.1066773, 0.486639644),
(898.0308792, 0.476374133),
(899.9550811, 0.466365094),
(901.879283, 0.456356055),
(904.7655858, 0.44583075),
(906.1125272, 0.436336648),
(909.3012046, 0.424564579),
(914.065895, 0.409750119),
(917.7539487, 0.394491568),
(921.6023525, 0.380853222),
(925.8249067, 0.366679269),
(931.8418555, 0.35267468),
(935.5528163, 0.341425964),
(939.4012201, 0.332008715),
(943.2496239, 0.323018918),
(947.0980277, 0.313174215),
(950.9464316, 0.303543239),
(954.7948354, 0.294339716),
(958.6432392, 0.284495014),
(962.491643, 0.274222859),
(966.3400468, 0.263950703),
(970.1884506, 0.253678548),
(974.0368544, 0.243192667),
(976.9231573, 0.232966579),
(981.0922614, 0.222436845),
(984.9406652, 0.210027425),
(987.8269681, 0.198262508),
(991.2477715, 0.185925807),
(994.7907464, 0.172560763),
(998.9140362, 0.160822106),
(1003.140408, 0.148144224),
(1007.710388, 0.136683396),
(1011.238091, 0.127010782),
(1017.331397, 0.116645384),
(1021.179801, 0.106629701),
(1026.952407, 0.096393647),
(1031.955332, 0.086074759),
(1038.497618, 0.077332132),
(1045.232325, 0.06705001),
(1052.929133, 0.057405746),
(1061.106991, 0.04775982),
(1072.491852, 0.037034188),
(1080.83006, 0.031021057),
]
)
REL_FULL_SENSITIVITY_FUNC = scipy.interpolate.interp1d(
REL_FULL_SENSITIVITY[:, 0], REL_FULL_SENSITIVITY[:, 1]
)
REL_IR_SENSITIVITY_FUNC = scipy.interpolate.interp1d(
REL_IR_SENSITIVITY[:, 0], REL_IR_SENSITIVITY[:, 1]
)
RAT_FUNC = lambda x: REL_IR_SENSITIVITY_FUNC(x) / REL_FULL_SENSITIVITY_FUNC(x)
def smooth(x, y, delta=1, N=10):
f = scipy.interpolate.interp1d(x, y)
xf = np.arange(x.min(), x.max(), delta / N)
yf = f(xf)
cumsum = np.cumsum(np.insert(yf, 0, 0))
rx = xf[int(N / 2) : -int(N / 2 - 1)]
ry = (cumsum[N:] - cumsum[:-N]) / float(N)
rf = scipy.interpolate.interp1d(rx, ry)
return rx, ry, rf
wave_length_range = np.arange(
max(REL_FULL_SENSITIVITY[:, 0].min(), REL_IR_SENSITIVITY[:, 0].min()),
min(REL_FULL_SENSITIVITY[:, 0].max(), REL_IR_SENSITIVITY[:, 0].max()),
)
rx, ry, rate_smooth = smooth(
wave_length_range, RAT_FUNC(wave_length_range), delta=20, N=10
)
diff = np.diff(ry)
diff = np.nan_to_num(diff / np.abs(diff))
diff[:-1][np.diff(diff) == 0] = 0
indexes = np.arange(len(diff))[diff.astype(bool)]
max_index_diff = np.argmax(np.diff(indexes))
lower_index = indexes[max_index_diff]
upper_index = indexes[max_index_diff + 1]
RATIO_TO_WAVELENGHT = scipy.interpolate.interp1d(
ry[lower_index:upper_index], rx[lower_index:upper_index]
)
def luminosity_splitter(var, instance, data, send_to_board=True):
var.default_setter(
var=var, instance=instance, data=data, send_to_board=send_to_board
)
sc = struct.pack("L", data)
instance.ch0 = struct.unpack("H", sc[:2])[0]
instance.ch1 = struct.unpack("H", sc[2:])[0]
try:
instance.estimated_wavelength = RATIO_TO_WAVELENGHT(instance.ch1 / instance.ch0)
except:
pass
tsl2591Gain_t = ArduinoEnum(
"tsl2591Gain_t",
{
0x00: ("TSL2591_GAIN_LOW", "low gain (1x)"),
0x10: ("TSL2591_GAIN_MED", "medium gain (25x)"),
0x20: ("TSL2591_GAIN_HIGH", "medium gain (428x)"),
0x30: ("TSL2591_GAIN_MAX", "max gain (9876x)"),
},
uint8_t,
)
tsl2591IntegrationTime_t = ArduinoEnum(
"tsl2591IntegrationTime_t",
{
0x00: ("TSL2591_INTEGRATIONTIME_100MS", "100 millis"),
0x01: ("TSL2591_INTEGRATIONTIME_200MS", "200 millis"),
0x02: ("TSL2591_INTEGRATIONTIME_300MS", "300 millis"),
0x03: ("TSL2591_INTEGRATIONTIME_400MS", "400 millis"),
0x04: ("TSL2591_INTEGRATIONTIME_500MS", "500 millis"),
0x05: ("TSL2591_INTEGRATIONTIME_600MS", "600 millis"),
},
uint8_t,
)
tsl2591Persist_t = ArduinoEnum(
"tsl2591Persist_t",
{
0: ("TSL2591_PERSIST_EVERY", "Every ALS cycle generates an interrupt"),
2: ("TSL2591_PERSIST_ANY", "Any value outside of threshold range"),
3: ("TSL2591_PERSIST_2", "2 consecutive values out of range"),
4: ("TSL2591_PERSIST_3", "3 consecutive values out of range"),
5: ("TSL2591_PERSIST_5", "5 consecutive values out of range"),
6: ("TSL2591_PERSIST_10", "10 consecutive values out of range"),
7: ("TSL2591_PERSIST_15", "15 consecutive values out of range"),
8: ("TSL2591_PERSIST_20", "20 consecutive values out of range"),
9: ("TSL2591_PERSIST_25", "25 consecutive values out of range"),
10: ("TSL2591_PERSIST_30", "30 consecutive values out of range"),
11: ("TSL2591_PERSIST_35", "35 consecutive values out of range"),
12: ("TSL2591_PERSIST_40", "40 consecutive values out of range"),
13: ("TSL2591_PERSIST_45", "45 consecutive values out of range"),
14: ("TSL2591_PERSIST_50", "50 consecutive values out of range"),
15: ("TSL2591_PERSIST_55", "55 consecutive values out of range"),
16: ("TSL2591_PERSIST_60", "60 consecutive values out of range"),
},
uint8_t,
)
class Adafruit_TSL2591(ArduinoClass):
class_name = "Adafruit_TSL2591"
include = '"Adafruit_TSL2591.h"'
begin = Function("begin", return_type=boolean)
enable = Function("enable")
disable = Function("disable")
calculateLux = Function(
"calculateLux", [(uint16_t, "ch0"), (uint16_t, "ch1")], return_type=float_
)
setGain = Function("setGain", [(tsl2591Gain_t, "gain")])
setTiming = Function("setTiming", [(tsl2591IntegrationTime_t, "integration")])
getLuminosity = Function("getLuminosity", [(uint8_t, "channel")], uint16_t)
getFullLuminosity = Function("getFullLuminosity", return_type=uint32_t)
getTiming = Function("getTiming", return_type=tsl2591IntegrationTime_t)
getGain = Function("getGain", return_type=tsl2591Gain_t)
clearInterrupt = Function("clearInterrupt")
getStatus = Function("getStatus", return_type=uint8_t)
registerInterrupt = Function(
"registerInterrupt",
[
(uint16_t, "lowerThreshold"),
(uint16_t, "upperThreshold"),
(tsl2591Persist_t, "persist"),
],
)
class Tsl2591(ArduinoBasicBoard):
FIRMWARE = 15633422980183442
adafruit_TSL2591 = Adafruit_TSL2591()
tsl = adafruit_TSL2591("tsl", uint32_t.random())
ch0 = python_variable(
"ch0", type=np.float, changeable=False, is_data_point=True, save=False
)
ch1 = python_variable(
"ch1", type=np.float, changeable=False, is_data_point=True, save=False
)
estimated_wavelength = python_variable(
"estimated_wavelength",
type=np.int,
changeable=False,
is_data_point=True,
save=False,
)
luminosity = arduio_variable(
"luminosity",
arduino_data_type=uint32_t,
is_data_point=True,
arduino_setter=False,
setter=luminosity_splitter,
save=False,
)
gain = arduio_variable(
"gain",
arduino_data_type=uint8_t,
allowed_values=tsl2591Gain_t,
arduino_setter=(tsl.setGain(COMMAND_FUNCTION_COMMUNICATION_ARGUMENTS[0][0])),
arduino_getter=(WRITE_DATA_FUNCTION(tsl.getGain(), "BYTEID")),
is_global_var=False,
)
integration_time = arduio_variable(
"integration_time",
arduino_data_type=uint8_t,
allowed_values=tsl2591IntegrationTime_t, # # arduino_setter="tsl.setTiming((tsl2591IntegrationTime_t) data[0]);",
arduino_getter=(WRITE_DATA_FUNCTION(tsl.getTiming(), "BYTEID")),
arduino_setter=(tsl.setTiming(COMMAND_FUNCTION_COMMUNICATION_ARGUMENTS[0][0])),
)
def __init__(self):
super().__init__()
def add_arduino_code(self, ad):
ad.loop.add_call(self.luminosity.set(self.tsl.getFullLuminosity()))
if __name__ == "__main__":
ins = Tsl2591()
ins.create_ino()
|
ArduinoBoardCollection
|
/ArduinoBoardCollection-0.1.1566386412.tar.gz/ArduinoBoardCollection-0.1.1566386412/arduino_board_collection_bu/boards/sensor_boards/light_sensors/tsl2591/board.py
|
board.py
|
from ArduinoCodeCreator.arduino_data_types import *
from arduino_board_collection.boards.sensor_boards.basic.analog_read_board.board import (
AnalogReadBoard,
)
from arduino_controller.basicboard.board import ArduinoBasicBoard
from arduino_controller.arduino_variable import arduio_variable
from arduino_controller.python_variable import python_variable
class ThermistorBoard(AnalogReadBoard):
FIRMWARE = 15650180050147572
thermistor_base_resistance = arduio_variable(
name="thermistor_base_resistance",
arduino_data_type=uint32_t,
eeprom=True,
default=10 ** 5,
)
reference_resistance = arduio_variable(
name="reference_resistance",
arduino_data_type=uint32_t,
eeprom=True,
default=10 ** 5,
)
temperature = python_variable(
"temperature", type=np.float, changeable=False, is_data_point=True, save=False
)
reference_temperature = python_variable(
"reference_temperature", type=np.float, default=298.15, minimum=0
)
a = python_variable("a", type=np.float, default=1.009249522e-03)
b = python_variable("b", type=np.float, default=2.378405444e-04)
c = python_variable("c", type=np.float, default=2.019202697e-07)
def pre_ini_function(self):
super().pre_ini_function()
self.analog_value.name = "thermistor_resistance"
self.analog_value.setter = self.resistance_to_temperature
@staticmethod
def resistance_to_temperature(var, instance, data, send_to_board=True):
var.default_setter(
var=var, instance=instance, data=data, send_to_board=send_to_board
)
try:
R2 = instance.reference_resistance * (1023.0 - data) / data
logR2 = np.log(R2)
T = 1.0 / (
instance.a + instance.b * logR2 + instance.c * logR2 * logR2 * logR2
)
instance.temperature = T
except ZeroDivisionError:
pass
if __name__ == "__main__":
ins = ThermistorBoard()
ins.create_ino()
|
ArduinoBoardCollection
|
/ArduinoBoardCollection-0.1.1566386412.tar.gz/ArduinoBoardCollection-0.1.1566386412/arduino_board_collection_bu/boards/sensor_boards/thermal/thermistor/board.py
|
board.py
|
from ArduinoCodeCreator.arduino_data_types import *
from arduino_board_collection.boards.sensor_boards.basic.analog_read_board2.board import (
AnalogReadBoard2,
)
from arduino_board_collection.boards.sensor_boards.thermal.thermistor.board import (
ThermistorBoard,
)
from arduino_controller.basicboard.board import ArduinoBasicBoard
from arduino_controller.arduino_variable import arduio_variable
from arduino_controller.python_variable import python_variable
def resistance_to_temperature(var, instance, data, send_to_board=True):
var.default_setter(
var=var, instance=instance, data=data, send_to_board=send_to_board
)
print(var)
try:
R2 = instance.reference_resistance * (1023.0 - data) / data
logR2 = np.log(R2)
T = 1.0 / (instance.a + instance.b * logR2 + instance.c * logR2 * logR2 * logR2)
instance.temperature = T
except ZeroDivisionError:
pass
class ThermistorBoard2(ThermistorBoard, AnalogReadBoard2):
FIRMWARE = 15650180050147573
thermistor_base_resistance2 = arduio_variable(
name="thermistor_base_resistance2",
arduino_data_type=uint32_t,
eeprom=True,
default=10 ** 5,
)
reference_resistance2 = arduio_variable(
name="reference_resistance2",
arduino_data_type=uint32_t,
eeprom=True,
default=10 ** 5,
)
temperature2 = python_variable(
"temperature2", type=np.float, changeable=False, is_data_point=True, save=False
)
reference_temperature2 = python_variable(
"reference_temperature2", type=np.float, default=298.15, minimum=0
)
a2 = python_variable("a2", type=np.float, default=1.009249522e-03)
b2 = python_variable("b2", type=np.float, default=2.378405444e-04)
c2 = python_variable("c2", type=np.float, default=2.019202697e-07)
def pre_ini_function(self):
super().pre_ini_function()
self.thermistor_base_resistance.name = (
self.thermistor_base_resistance.name + "1"
)
self.reference_resistance.name = self.reference_resistance.name + "1"
self.temperature.name = self.temperature.name + "1"
self.reference_temperature.name = self.reference_temperature.name + "1"
self.a.name = self.a.name + "1"
self.b.name = self.b.name + "1"
self.c.name = self.c.name + "1"
self.analog_value2.name = self.analog_value.name + "2"
self.analog_value.name = self.analog_value.name + "1"
self.analog_value2.setter = self.resistance_to_temperature2
@staticmethod
def resistance_to_temperature2(var, instance, data, send_to_board=True):
var.default_setter(
var=var, instance=instance, data=data, send_to_board=send_to_board
)
try:
R2 = instance.reference_resistance2 * (1023.0 - data) / data
logR2 = np.log(R2)
T = 1.0 / (
instance.a2 + instance.b2 * logR2 + instance.c2 * logR2 * logR2 * logR2
)
instance.temperature2 = T
except ZeroDivisionError:
pass
if __name__ == "__main__":
ins = ThermistorBoard2()
ins.create_ino()
|
ArduinoBoardCollection
|
/ArduinoBoardCollection-0.1.1566386412.tar.gz/ArduinoBoardCollection-0.1.1566386412/arduino_board_collection_bu/boards/sensor_boards/thermal/thermistor2/board.py
|
board.py
|
import time
from arduino_board_collection.boards.sensor_boards.thermal.thermistor.board import (
ThermistorBoard,
)
from arduino_board_collection.boards.signal_boards.switches.relay.board import (
RelayBoard,
)
from arduino_controller.basicboard.board import ArduinoBasicBoard
from ArduinoCodeCreator.arduino_data_types import *
from arduino_controller.arduino_variable import arduio_variable
from arduino_controller.python_variable import python_variable
try:
_current_time = time.monotonic
except AttributeError:
_current_time = time.time
def pdi_temperature(var, instance, data):
var.default_setter(var, instance, data)
if instance.running:
on_time = instance.pid(data)
print(on_time)
if on_time is not None:
if on_time > instance.threshold:
instance.open = False
else:
instance.open = True
else:
instance.reset()
class RelayThermistorBoard(ThermistorBoard, RelayBoard):
FIRMWARE = 15650261815701852
target_temperature = python_variable(
"target_temperature", type=np.float, default=298.15, minimum=0
)
max_temperature = python_variable(
"max_temperature", type=np.float, default=500, minimum=0
)
min_temperature = python_variable(
"min_temperature", type=np.float, default=0, minimum=0
)
max_on_time = 100
min_on_time = 0
threshold = python_variable(
"threshold", type=np.float, default=50, minimum=0, maximum=100
)
running = python_variable("running", type=np.bool, default=False, save=False)
kp = python_variable("kp", type=np.float, default=1)
ki = python_variable("ki", type=np.float)
kd = python_variable("kd", type=np.float)
def __init__(self):
super().__init__()
self.get_module_var_by_name("temperature").setter = pdi_temperature
self._last_time = _current_time()
self._last_input = None
self._integral = 0
def reset(self):
self._last_time = _current_time()
self._last_input = None
self._integral = 0
def pid(self, input):
if self._last_input is None:
self._last_time = _current_time()
time.sleep(0.01)
now = _current_time()
if now - self._last_time:
dt = now - self._last_time
else:
return None
error = self.target_temperature - input
d_input = input - (self._last_input if self._last_input is not None else input)
# compute integral and derivative terms
proportional = self.kp * error
self._integral += self.ki * error * dt
self._integral = min(
self.max_on_time, max(self.min_on_time, self._integral)
) # avoid integral windup
derivative = -self.kd * d_input / dt
# compute final output
output = proportional + self._integral + derivative
output = min(self.max_on_time, max(self.min_on_time, output))
self._last_input = input
self._last_time = now
return output
if __name__ == "__main__":
ins = RelayThermistorBoard()
ins.create_ino()
|
ArduinoBoardCollection
|
/ArduinoBoardCollection-0.1.1566386412.tar.gz/ArduinoBoardCollection-0.1.1566386412/arduino_board_collection_bu/boards/sensor_signal_boards/pid_boards/relay_thermistor_pid/board.py
|
board.py
|
import json
import logging
import os
import re
import shutil
try:
# python 2
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import HTTPServer as BaseHTTPServer
except ImportError:
# python 3
from http.server import HTTPServer as BaseHTTPServer, SimpleHTTPRequestHandler
class BasicRequestHandler(SimpleHTTPRequestHandler):
def __init__(self, arduino_controll_server, request, client_address, server):
self.arduino_controll_server = arduino_controll_server
super().__init__(request, client_address, server)
def translate_path(self, path):
for regpath,rh in self.arduino_controll_server.requesthandler.items():
if re.match(regpath, path):
return rh.translate_path(self, path)
return SimpleHTTPRequestHandler.translate_path(self, path)
class ArduinoControllServer():
def __init__(self,port=80, socketport=8888, **kwargs):
self.socketport = socketport
self.port = port
self.requesthandler={}
if "www_data" in kwargs:
self.WWW_DATA_DIR = os.path.abspath(kwargs['www_data'])
del kwargs['www_data']
else:
self.WWW_DATA_DIR = os.path.join(os.path.expanduser('~'), "www-data")
os.makedirs(self.WWW_DATA_DIR, exist_ok=True)
os.chdir(self.WWW_DATA_DIR)
if "logger" in kwargs:
self.logger = kwargs['logger']
del kwargs['logger']
else:
self.logger = logging.getLogger("arduinocontrollserver")
kwargs['socketport']=socketport
with open("serverdata.js", "w+") as file:
file.write("var serverdata = " + json.dumps(kwargs) + ";")
def start(self):
httpd = BaseHTTPServer(("", self.port), lambda request, client_address, server: BasicRequestHandler(arduino_controll_server=self,request=request, client_address=client_address, server=server))
self.logger.info("serving at port " + str(self.port))
httpd.serve_forever()
def get_www_data_path(self):
from arduinocontrollserver import www_data
return os.path.abspath(os.path.dirname(www_data.__file__))
def deploy(self,path,parent=None):
recursive_overwrite(os.path.abspath(path),os.path.abspath(os.path.join(self.WWW_DATA_DIR,parent if parent is not None else "")),
ignore=lambda src,files:set([f for f in files if ("."+f).split(".")[-1] in ["py",".so","__pycache__"]])
)
def recursive_overwrite(src, dest, ignore=None):
if os.path.isdir(src):
if not os.path.isdir(dest):
os.makedirs(dest)
files = os.listdir(src)
if ignore is not None:
ignored = ignore(src, files)
else:
ignored = set()
for f in files:
if f not in ignored:
recursive_overwrite(os.path.join(src, f),
os.path.join(dest, f),
ignore)
else:
shutil.copyfile(src, dest)
if __name__ == "__main__":
server = ArduinoControllServer(port=80,socketport=8888)
server.start()
|
ArduinoControllServer
|
/ArduinoControllServer-0.1.1555408086-py3-none-any.whl/arduinocontrollserver/arduinocontrollserver.py
|
arduinocontrollserver.py
|
import numpy as np
STARTBYTE = b"\x02"
STARTBYTEPOSITION = 0
COMMANDBYTEPOSITION = 1
LENBYTEPOSITION = 2
DATABYTEPOSITION = 3
np.seterr(over="ignore")
def generate_checksum(array):
sum1 = np.uint8(0)
sum2 = np.uint8(0)
for i in np.array(array, dtype=np.uint8):
sum1 = sum1 + i
sum2 = sum2 + sum1
return sum2 * np.uint16(256) + sum1
def generate_port_message(cmd, datalength, *args):
# print("W: ",cmd,datalength,args)
assert len(args) >= datalength
return generate_request(cmd, args[:datalength])
def generate_request(command, data):
a = [2, command, len(data), *data]
# print(generate_checksum(a))
a.extend(generate_checksum(a).tobytes())
# print(bytearray(a))
return bytearray(a)
def validate_buffer(port):
# print(port.read_buffer)
try:
firststart = port.read_buffer.index(STARTBYTE)
except ValueError:
firststart = 0
port.read_buffer = []
bufferlength = len(port.read_buffer[firststart:])
if bufferlength >= DATABYTEPOSITION + 2:
datalength = ord(port.read_buffer[firststart + LENBYTEPOSITION])
if bufferlength >= DATABYTEPOSITION + datalength + 2:
databuffer = port.read_buffer[
firststart : firststart + DATABYTEPOSITION + datalength
]
checksumbuffer = port.read_buffer[
firststart
+ DATABYTEPOSITION
+ datalength : firststart
+ DATABYTEPOSITION
+ datalength
+ 2
]
# print(databuffer)
# print(checksumbuffer)
databuffer = np.array([ord(i) for i in databuffer], dtype=np.uint8)
checksumbuffer = np.array([ord(i) for i in checksumbuffer], dtype=np.uint8)
# print(databuffer)
# print(checksumbuffer)
checksum = np.frombuffer(checksumbuffer, dtype=np.uint16)[0]
generated_cs = generate_checksum(databuffer)
# print("cs: ",checksum,generated_cs)
if checksum == generated_cs:
port.board.receive_from_port(
cmd=databuffer[COMMANDBYTEPOSITION],
data=b"".join(databuffer[DATABYTEPOSITION:]),
)
port.read_buffer = port.read_buffer[
firststart + DATABYTEPOSITION + datalength + 2 :
]
|
ArduinoController
|
/ArduinoController-0.1.1568726333.tar.gz/ArduinoController-0.1.1568726333/arduino_controller/portrequest.py
|
portrequest.py
|
import numpy as np
import filter_dict
class StrucTypeNotFoundException(Exception):
pass
class ModuleVarianbleStruct:
def __init__(
self,
minimum=None,
maximum=None,
python_type=int,
html_input="number",
html_attributes=None,
default_value=0,
):
if html_attributes is None:
html_attributes = dict()
self.value = default_value
self.html_attributes = html_attributes
self.html_input = html_input
self.python_type = python_type
self.maximum = maximum
self.minimum = minimum
DEFAULT_STRUCTURES = {
**{
nptype: ModuleVarianbleStruct(
minimum=np.iinfo(nptype).min,
maximum=np.iinfo(nptype).max,
python_type=nptype,
html_input="number",
)
for nptype in [
np.int8,
np.int16,
np.int32,
np.int64,
np.uint8,
np.uint16,
np.uint32,
np.uint64,
np.int,
]
},
**{
nptype: ModuleVarianbleStruct(python_type=nptype, html_input="number")
for nptype in [np.double, np.float, np.float32, np.float16, np.float64]
},
bool: ModuleVarianbleStruct(python_type=bool, html_input="checkbox"),
}
class ModuleVariable:
def __init__(
self,
name,
python_type,
board,
html_input=None,
var_structure=None,
save=None,
getter=None,
setter=None,
default=None,
minimum=None,
maximum=None,
is_data_point=None,
allowed_values=None,
nullable=None,
changeable=None,
html_attributes=None,
):
if save is None:
save = True
if is_data_point is None:
is_data_point = False
if nullable is None:
nullable = False
if html_attributes is None:
html_attributes = {}
self.html_attributes = html_attributes
self.board = board
self.name = str(name)
self.python_type = python_type
self.save = save
self.is_data_point = is_data_point
self.html_input = html_input
self.allowed_values = allowed_values
self.nullable = nullable
self.attributes = {}
self.return_self = True
if not hasattr(self, "structure_list"):
self.structure_list = DEFAULT_STRUCTURES
if var_structure is not None:
assert isinstance(
var_structure, ModuleVarianbleStruct
), "var_structure not of class ModuleVarianbleStruct"
self.var_structure = var_structure
else:
self.var_structure = self.structure_list.get(python_type)
if self.var_structure is None:
self.var_structure = self.structure_list.get(str(python_type))
if self.var_structure is None:
raise StrucTypeNotFoundException(
"Struct equivalent not found for {}({}) please define manually".format(
name, python_type
)
)
self.default = 0 if default is None else default
self.maximum = self.var_structure.maximum if maximum is None else maximum
self.minimum = self.var_structure.minimum if minimum is None else minimum
self.value = self.default
self.setter = (
None
if setter is False
else (self.default_setter if setter is None else setter)
)
self.getter = (
None
if setter is False
else (self.default_getter if getter is None else getter)
)
self.changeable = (
changeable
if changeable is not None
else (False if self.setter is None else True)
)
def default_getter(self, instance):
return self.value
def default_setter(self, var, instance, data):
if data is None and not var.nullable:
return
if data is not None:
data = var.python_type(data)
# print(self.name,instance,getattr(instance,self.name))
if var.allowed_values is not None:
# if value is not allowed by allowed_values
if data not in var.allowed_values:
# select nearest allowed value
data = min(var.allowed_values, key=lambda x: abs(x - data))
if data is not None:
if var.minimum is not None:
if data < var.minimum:
data = var.minimum
if var.maximum is not None:
if data > var.maximum:
data = var.maximum
var.value = data
if var.is_data_point:
var.send_data_point(data)
return data
def send_data_point(self, data):
self.board.data_point(self.name, data)
def set_value(self, instance, value):
self.setter(var=self, instance=instance, data=value)
def get_value(self, instance, owner):
if self.return_self or self.getter is None:
return self
return self.getter(instance)
def modulvar_getter_modification(self, newfunc):
pregetter = self.getter
def newgetter(*args, **kwargs):
return newfunc(pregetter(*args, **kwargs))
self.getter = newgetter
def modulvar_setter_modification(self, newfunc):
presetter = self.setter
def newsetter(data=0, *args, **kwargs):
data = newfunc(self.python_type(data))
return presetter(data=data, *args, **kwargs)
self.setter = newsetter
def data_point_modification(self, newfunc):
presetter = self.send_data_point
def newsetter(data):
data = newfunc(self.python_type(data))
return presetter(data=data)
self.send_data_point = newsetter
def _generate_html_input(self):
if self.changeable:
if self.allowed_values is not None:
html_input = '<select name="{}" {}>{}</select>'.format(
self.name,
" ".join(
[
str(key) + '="' + str(val) + '"'
for key, val in {
**self.var_structure.html_attributes,
**self.html_attributes,
}.items()
]
),
"".join(
[
'<option value="{}" {}>{}</option>'.format(
allowed_value,
" selected" if allowed_value == self.value else "",
self.allowed_values[allowed_value]
if isinstance(self.allowed_values, dict)
else allowed_value,
)
for allowed_value in self.allowed_values
]
),
)
# + str(
# self.allowed_values[allowed] if isinstance(self.allowed_values, dict) else allowed) +
# html_input = '<select name="' + self.name + '" ' + ' '.join(
# [str(key) + '="' + str(val) + '"' for key, val in self.var_structure.html_attributes.items()]) + ' >' + \
# ''.join(['<option value="' + str(allowed) + '" ' + str(
# " selected" if allowed == self.value else "") + '>' + str(
# self.allowed_values[allowed] if isinstance(self.allowed_values,
# dict) else allowed) + '</option>' for
# allowed in self.allowed_values]) + \
# '</select>'
else:
html_input = (
'<input type="'
+ self.var_structure.html_input
+ '" min="'
+ str(self.minimum)
+ '" max="'
+ str(self.maximum)
+ '" name="modul_variable_input_'
+ self.name
+ '" value="{{value}}" '
+ " ".join(
[
str(key) + '="' + str(val) + '"'
for key, val in {
**self.var_structure.html_attributes,
**self.html_attributes,
}.items()
]
)
+ (" readonly" if self.setter is None else "")
+ ">"
)
else:
html_input = ""
if self.is_data_point:
html_input += '<input type={} name="data_point_{}" value="{{value}}" readonly disabled>'.format(
self.var_structure.html_input, self.name
)
if self.allowed_values is None:
self.attributes["html_input"] = html_input
return html_input
def get_html_input(self):
return self.attributes.get("html_input", self._generate_html_input())
def set_html_input(self, html_input):
if html_input is not None:
self.attributes["html_input"] = html_input
html_input = property(get_html_input, set_html_input)
class ModuleVariableTemplate:
targetclass = ModuleVariable
def __init__(self, name, python_type, **kwargs):
for key, val in kwargs.items():
setattr(self, key, val)
self.name = name
self.python_type = python_type
self.board = None
def initialize(self, instance, name):
self.board = instance
new_var = filter_dict.call_method(self.targetclass, kwargs=self.__dict__)
new_var.name = name
setattr(instance, name, new_var)
return new_var
|
ArduinoController
|
/ArduinoController-0.1.1568726333.tar.gz/ArduinoController-0.1.1568726333/arduino_controller/modul_variable.py
|
modul_variable.py
|
import re
import numpy as np
from .portrequest import generate_port_message
class PortCommand:
def __init__(
self,
module,
name,
python_receivetype=None,
python_sendtype=None,
receivefunction=None,
sendfunction=None,
arduino_function=None,
):
self.module = module
self.sendlength = (
np.array([], dtype=python_sendtype).itemsize
if python_sendtype is not None
else 0
)
self.receivelength = (
np.array([], dtype=python_receivetype).itemsize
if python_receivetype is not None
else 0
)
# print(name,self.sendlength,self.receivelength)
self.python_sendtype = python_sendtype
self.python_receivetype = python_receivetype
if sendfunction is None:
sendfunction = self.defaultsendfunction
self.sendfunction = sendfunction
self.receivefunction = receivefunction
self.name = re.sub(r"\s+", "", name, flags=re.UNICODE)
self.byteid = module.first_free_byte_id
# print(arduino_function)
# print(self.byteid, self.name)
# arduino_function.byte_id=self.byteid
self.set_arduino_function(arduino_function)
def set_arduino_function(self, arduino_function):
if arduino_function is not None:
self.arduino_function = arduino_function
self.arduino_function.name = "{}_{}".format(
self.arduino_function.name, self.byteid
)
self.module.byte_ids.add_possibility(self.arduino_function, self.byteid)
else:
self.arduino_function = None
def defaultsendfunction(self, numericaldata=None):
if self.python_sendtype is not None:
if numericaldata is None:
data = np.frombuffer(bytearray(), dtype=self.python_sendtype).tobytes()
else:
data = np.array([numericaldata], dtype=self.python_sendtype).tobytes()
else:
data = bytearray()
self.module.serial_port.write(
bytearray(generate_port_message(self.byteid, self.sendlength, *data))
)
def receive(self, nparray):
# print(self.python_receivetype,nparray)
# print(nparray,self.python_receivetype)
# print(self.name,np.frombuffer(nparray, dtype=self.python_receivetype)[0])
self.receivefunction(
self.module,
np.frombuffer(nparray, dtype=self.python_receivetype)[0]
# struct.unpack(self.python_receivetype, bytearray)[0]
)
|
ArduinoController
|
/ArduinoController-0.1.1568726333.tar.gz/ArduinoController-0.1.1568726333/arduino_controller/portcommand.py
|
portcommand.py
|
import logging
import threading
import time
import serial
import filter_dict
from arduino_controller.serialreader.serialreader import DATAPOINT_RESOLUTION
from .parseboards import board_by_firmware
from .basicboard.board import BasicBoard
from .portrequest import validate_buffer
PORT_READ_TIME = 0.01
BAUDRATES = (
9600,
115200,
# 19200,
# 38400,
# 57600,
# 230400,
# 460800,
# 500000,
# 576000,
# 921600,
# 1000000,
# 1152000,
# 1500000,
# 2000000,
# 2500000,
# 3000000,
# 3500000,
# 4000000,
# 4000000,
)
class PortIdentifyError(Exception):
pass
class FirmwareNotFoundError(Exception):
pass
class SerialPortDataTarget:
def __init__(self):
pass
def port_data_point(self, key, x, y, port, board):
pass
def port_identified(self, port):
pass
def board_update(self, board_data):
pass
def port_opened(self, port, baud):
pass
def port_closed(self, port):
pass
def set_board(self, port, board):
pass
class SerialPort(serial.Serial):
def __init__(
self, serial_reader, port, config=None, logger=None, baudrate=9600, **kwargs
):
self.serial_reader = serial_reader
self.data_targets = set([])
self.datapoint_resolution = DATAPOINT_RESOLUTION
if logger is None:
logger = logging.getLogger("serial_reader " + port)
self.logger = logger
self.board = None
self.work_thread = None
self.update_thread = None
self.read_buffer = []
self.time = time.time()
if config is None:
config = serial_reader.config
self.config = config
try:
super().__init__(port, baudrate=baudrate, timeout=0, **kwargs)
except Exception as e:
serial_reader.deadports.add(port)
self.logger.exception(e)
return
self.logger.info("port found " + self.port)
serial_reader.connected_ports.add(self)
self.to_write = []
self.start_read()
newb = board_by_firmware(
config.get("portdata", self.port, "firmware", default=0)
)
if newb is not None:
self.set_board(newb["classcaller"])
else:
self.set_board(BasicBoard)
def add_data_target(self, data_target=None):
if data_target is not None:
self.data_targets.add(data_target)
def remove_data_target(self, data_target):
if data_target in self.data_targets:
self.data_targets.remove(data_target)
def board_function(self, board_cmd, **kwargs):
# try:
getattr(self.board, board_cmd)(**kwargs)
# except A:
# self.logger.exception(Exception)
def set_board_attribute(self, attribute, value):
try:
setattr(self.board, attribute, value)
except:
self.logger.exception(Exception)
def add_data_point(self, board, key, y, x=None):
t = (
int(1000 * (time.time() - self.time) / self.datapoint_resolution)
* self.datapoint_resolution
)
if x is None:
x = t
try:
for data_target in self.data_targets:
filter_dict.call_method(
target=data_target.port_data_point,
kwargs=dict(key=key, x=x, y=y, port=board.port, board=board.id),
)
except RuntimeError:
pass
def set_board(self, board_class):
self.board = board_class()
self.board.set_serial_port(self)
time.sleep(2)
self.board.identify()
if not self.board.identified:
self.stop_read()
self.serial_reader.ignored_ports.add(self.port)
self.logger.error("unable to identify " + self.port)
raise PortIdentifyError()
if self.board.FIRMWARE != self.board.firmware:
self.logger.warning("firmware detected {}".format(self.board.firmware))
newb = board_by_firmware(self.board.firmware)
if newb is not None:
return self.set_board(newb["classcaller"])
else:
self.stop_read()
self.serial_reader.ignored_ports.add(self.port)
self.logger.error("firmware not found " + str(self.board.firmware))
raise FirmwareNotFoundError()
# self.board.specific_identification()
if not self.board.identified:
self.stop_read()
self.serial_reader.ignored_ports.add(self.port)
raise ValueError(
"unable to specificidentify "
+ self.port
+ "with firmware:"
+ str(self.board.firmware)
)
self.logger.info(str(self.port) + " identified ")
self.serial_reader.identified_ports.add(self)
self.config.put("portdata", self.port, "baud", value=self.baudrate)
self.config.put("portdata", self.port, "firmware", value=self.board.firmware)
self.board.restore(self.config.get("board_data", self.board.id, default={}))
self.board.get_portcommand_by_name("identify").sendfunction(True)
for data_target in self.serial_reader.data_targets:
filter_dict.call_method(
data_target.port_identified, kwargs={"port": self.port}
)
return True
def board_updater(self):
while self.is_open:
if self.board is not None:
self.send_board_data()
time.sleep(self.board.update_time)
def send_board_data(self, **kwargs):
if self.board is not None:
if self.board.identified:
data = self.board.save()
self.config.put("board_data", self.board.id, value=data)
data["firmware"] = self.board.firmware
data["id"] = self.board.id
data["class"] = self.board.CLASSNAME
msg_d = dict(board_data=data, **kwargs)
for data_target in self.data_targets:
filter_dict.call_method(data_target.board_update, kwargs=msg_d)
self.logger.debug(msg_d)
def work_port(self):
while self.is_open:
try:
while len(self.to_write) > 0:
t = self.to_write.pop()
self.logger.debug("write to " + self.port + ": " + str(t))
super().write(t)
if self.is_open:
c = self.read()
while len(c) > 0:
# print(ord(c),c)
self.read_buffer.append(c)
validate_buffer(self)
if not self.is_open:
break
c = self.read()
# except serial.serialutil.SerialException as e:
# self.logger.exception(e)
# except AttributeError:
# break
except Exception as e:
self.logger.exception(e)
break
time.sleep(PORT_READ_TIME)
# print(self.is_open)
self.logger.error("work_port stopped")
self.stop_read()
def start_read(self):
self.logger.info("port opened " + self.port)
for data_target in self.serial_reader.data_targets:
filter_dict.call_method(
data_target.port_opened,
kwargs={"port": self.port, "baud": self.baudrate},
)
if not self.is_open:
self.open()
self.work_thread = threading.Thread(target=self.work_port)
self.update_thread = threading.Thread(target=self.board_updater)
self.work_thread.start()
self.update_thread.start()
def write(self, data):
self.to_write.append(data)
def stop_read(self):
self.close()
try:
self.work_thread.join()
except (RuntimeError, AttributeError):
pass
self.work_thread = None
try:
self.update_thread.join()
except (RuntimeError, AttributeError):
pass
self.close()
self.update_thread = None
self.logger.info("port closed " + self.port)
for data_target in self.serial_reader.data_targets:
filter_dict.call_method(data_target.port_closed, kwargs={"port": self.port})
if self in self.serial_reader.connected_ports:
self.serial_reader.connected_ports.remove(self)
if self in self.serial_reader.identified_ports:
self.serial_reader.identified_ports.remove(self)
del self
# def update(self, **kwargs):
# if self.board is not None:
# if self.board.id is not None:
# self.board.restore(**kwargs)
# self.send_board_data(force_update=True)
def get_board(self, data_target=None):
if data_target is None:
return
board = self.board.get_board()
filter_dict.call_method(
data_target.set_board, kwargs={"port": self.port, "board": board}
)
def open_serial_port(**kwargs):
try:
return SerialPort(**kwargs)
except (PortIdentifyError, FirmwareNotFoundError):
return None
|
ArduinoController
|
/ArduinoController-0.1.1568726333.tar.gz/ArduinoController-0.1.1568726333/arduino_controller/serialport.py
|
serialport.py
|
import filter_dict
from ArduinoCodeCreator import arduino_data_types
from ArduinoCodeCreator.arduino import Arduino, Eeprom
from ArduinoCodeCreator.basic_types import Variable as ACCArdVar, Function, ArduinoEnum
from arduino_controller.modul_variable import ModuleVariable, ModuleVariableTemplate
class ArduinoVariable(ACCArdVar, ModuleVariable):
def __init__(
self,
# for ArduinoVariable
board,
name,
arduino_data_type=None,
default=None,
# for module_variable
html_input=None,
save=None,
getter=None,
setter=None,
minimum=None,
maximum=None,
is_data_point=None,
allowed_values=None,
arduino_getter=None,
arduino_setter=None,
eeprom=None,
changeable=None,
add_to_code=None,
html_attributes=None,
):
# defaults
if arduino_data_type is None:
arduino_data_type = arduino_data_types.uint8_t
if save is None:
save = True
if is_data_point is None:
is_data_point = False
if eeprom is None:
eeprom = False
if add_to_code is None:
add_to_code = True
ACCArdVar.__init__(self, type=arduino_data_type, value=default, name=name)
# self.add_to_code = add_to_code
if is_data_point and setter is False:
setter = None
changeable = False
if eeprom:
save = False
self.add_to_code = add_to_code
if isinstance(allowed_values, ArduinoEnum):
allowed_values = {
key: val[1] for key, val in allowed_values.possibilities.items()
}
ModuleVariable.__init__(
self,
name=self.name,
python_type=self.type.python_type,
board=board,
html_input=html_input,
save=save,
getter=getter,
setter=setter,
default=default,
minimum=minimum,
maximum=maximum,
is_data_point=is_data_point,
allowed_values=allowed_values,
nullable=False,
changeable=changeable
if changeable is not None
else arduino_setter != False,
html_attributes=html_attributes,
)
self.eeprom = eeprom
from arduino_controller.basicboard.board import (
COMMAND_FUNCTION_COMMUNICATION_ARGUMENTS,
)
self.arduino_setter = (
None
if arduino_setter is False
else Function(
arguments=COMMAND_FUNCTION_COMMUNICATION_ARGUMENTS,
name="set_{}".format(self),
code=self.generate_arduino_setter()
if arduino_setter is None
else arduino_setter,
)
)
self.arduino_getter = (
None
if arduino_getter is False
else self.generate_arduino_getter(arduino_getter)
)
def modulvar_getter_modification(self, newfunc):
pregetter = self.getter
def newgetter(*args, **kwargs):
return newfunc(pregetter(*args, **kwargs))
self.getter = newgetter
def modulvar_setter_modification(self, newfunc):
presetter = self.setter
def newsetter(data=0, send_to_board=True, *args, **kwargs):
if send_to_board:
data = newfunc(self.python_type(data))
return presetter(data=data, *args, **kwargs)
self.setter = newsetter
@staticmethod
def default_setter(var, instance, data, send_to_board=True):
data = super().default_setter(var=var, instance=instance, data=data)
if var.arduino_setter is not None:
if send_to_board:
var.board.get_portcommand_by_name("set_" + var.name).sendfunction(data)
def set_without_sending_to_board(self, instance, data):
self.setter(var=self, instance=instance, data=data, send_to_board=False)
def generate_arduino_setter(self):
from arduino_controller.basicboard.board import (
COMMAND_FUNCTION_COMMUNICATION_ARGUMENTS,
)
functions = []
if self.add_to_code:
functions.append(
Arduino.memcpy(
self.to_pointer(),
COMMAND_FUNCTION_COMMUNICATION_ARGUMENTS[0],
self.type.byte_size,
)
)
if self.eeprom:
functions.append(Eeprom.put(self.board.eeprom_position.get(self), self))
return functions
def generate_arduino_getter(self, arduino_getter):
from arduino_controller.basicboard.board import (
WRITE_DATA_FUNCTION,
COMMAND_FUNCTION_COMMUNICATION_ARGUMENTS,
)
f = Function(
arguments=COMMAND_FUNCTION_COMMUNICATION_ARGUMENTS,
name="get_{}".format(self),
code=() if arduino_getter is None else arduino_getter,
)
if arduino_getter is None:
if self.add_to_code:
f.add_call(WRITE_DATA_FUNCTION(self, self.board.byte_ids.get(f)))
return f
class ArduinoVariableTemplate(ModuleVariableTemplate):
targetclass = ArduinoVariable
def __init__(self, name, arduino_data_type=arduino_data_types.uint8_t, **kwargs):
super().__init__(
name=name,
python_type=arduino_data_type.python_type,
arduino_data_type=arduino_data_type,
**kwargs
)
arduio_variable = ArduinoVariableTemplate
|
ArduinoController
|
/ArduinoController-0.1.1568726333.tar.gz/ArduinoController-0.1.1568726333/arduino_controller/arduino_variable.py
|
arduino_variable.py
|
import os
import sys
import threading
import time
import pandas as pd
import numpy as np
class DataLogger:
def __init__(self):
self._df = pd.DataFrame()
self._min_y_diff = {}
self._last_added_data = {}
self._last_not_added_data = {}
def set_min_y_diff(self, key, delta):
self._min_y_diff[key] = delta
def get_serializable_data(self, key=None):
data = self.get_data(key=key)
for key in data.columns:
if self._last_not_added_data[key] is not None:
if self._last_not_added_data[key][0] not in data.index:
data.loc[self._last_not_added_data[key][0]] = np.nan
data[key][
self._last_not_added_data[key][0]
] = self._last_not_added_data[key][1]
return data.to_dict()
def get_data(self, key=None):
if key is None:
return self._df.copy()
else:
if key not in self._df.columns:
return pd.DataFrame()
return self._df[key].copy()
def clear_data(self):
self._df = pd.DataFrame()
self._last_added_data = {}
self._last_not_added_data = {}
def add_datapoint(self, key, y, x=None, force=False):
if x is None:
x = int(time.time() * 1000)
if key not in self._df.columns:
self._df[key] = np.nan
self._last_not_added_data[key] = None
self._last_added_data[key] = None
self._min_y_diff[key] = 0
add_data = True
if self._last_added_data[key] is not None:
if (
abs(y - self._last_added_data[key][1]) <= self._min_y_diff[key]
and not force
):
self._last_not_added_data[key] = (x, y)
add_data = False
else:
if self._last_not_added_data[key] is not None:
if self._last_not_added_data[key][0] not in self._df.index:
self._df.loc[self._last_not_added_data[key][0]] = np.nan
self._df[key][
self._last_not_added_data[key][0]
] = self._last_not_added_data[key][1]
if add_data:
if x not in self._df.index:
self._df.loc[x] = np.nan
self._df[key][x] = y
self._last_added_data[key] = (x, y)
self._last_not_added_data[key] = None
return key, x, y
return None, None, None
def save(self, file, header_dict={}):
header = "\n".join(
["#{}={}".format(key, value) for key, value in header_dict.items()]
)
with open(file, "w+") as f:
for line in header:
f.write(line)
self._df.to_csv(f)
|
ArduinoController
|
/ArduinoController-0.1.1568726333.tar.gz/ArduinoController-0.1.1568726333/arduino_controller/datalogger.py
|
datalogger.py
|
import json
import logging
import os
import threading
import time
import filter_dict
from arduino_controller import parseboards
from arduino_controller.datalogger import DataLogger
from arduino_controller.serialport import SerialPortDataTarget
from arduino_controller.serialreader.serialreader import SerialReaderDataTarget
from json_dict import JsonDict
def api_run_fuction(func):
def func_wrap(self, *args, **kwargs):
if self.running:
return False
self.running = True
self.pause = False
self.logger.info("start running operation")
try:
func(self, *args, **kwargs)
except Exception as e:
self.logger.exception(e)
self.stop_run()
return False
self.logger.info("end running operation")
self.stop_run()
return True
return func_wrap
def api_function(visible=True, **kwargs):
def func_wrap(func):
def api_func_warper(*args, blocking=False, **kwargs):
if not blocking:
t = threading.Thread(target=func, args=args, kwargs=kwargs)
t.start()
return t
else:
return func(*args, **kwargs)
api_func_warper.api_function = True
api_func_warper.visible = visible
for n, t in kwargs.items():
setattr(api_func_warper, n, t)
return api_func_warper
return func_wrap
class BoardApi(SerialReaderDataTarget, SerialPortDataTarget):
required_boards = []
STATUS = {
0: "ok",
1: "not all boards linked",
2: "program running",
3: "program paused",
}
def port_data_point(self, key, x, y, port, board):
# board = str(board)
# if board not in self._data:
# self._data[board]={}
# self._data[board][key]=y
self._data[key] = y
def __init__(self, serial_reader=None, config=None):
"""
:type serial_reader: SerialReader
"""
super().__init__()
self._on_stop_functions = []
self.data_logger = DataLogger()
self._data = dict()
self.running = False
self.pause = False
self._ws_targets = set()
self.logger = logging.getLogger(self.__class__.__name__)
self.logger.info("start API {}".format(self.__class__.__name__))
self._serial_reader = None
self.config = (
JsonDict(
os.path.join(
os.path.expanduser("~"),
".{}".format(self.__class__.__name__),
"portdata.json",
)
)
if config is None
else config
)
self.possible_boards = [[] for board in self.required_boards]
if (
self.config.get("api_name", default=self.__class__.__name__)
!= self.__class__.__name__
):
self.config.data = {}
self.config.put("api_name", value=self.__class__.__name__)
self.config.put(
"linked_boards", value=[None for board in self.required_boards]
)
self.linked_boards = [None for board in self.required_boards]
if len(
self.config.get(
"linked_boards",
default=[b.id if b is not None else None for b in self.linked_boards],
)
) != len(self.linked_boards):
self.config.put(
"linked_boards", value=[None for board in self.required_boards]
)
for board in self.required_boards:
parseboards.add_board(board)
self.serial_reader = serial_reader
def __str__(self):
return self.__class__.__name__
def get_serial_reader(self):
return self._serial_reader
def set_serial_reader(self, serial_reader):
"""
:type serial_reader: SerialReader
"""
if self._serial_reader is not None:
self._serial_reader.remove_data_target(self)
if serial_reader is not None:
serial_reader.add_data_target(self)
self._serial_reader = serial_reader
serial_reader = property(get_serial_reader, set_serial_reader)
def set_ports(
self, available_ports, ignored_ports, connected_ports, identified_ports
):
proposed_linked_boards = [
int(b) if b is not None else b
for b in self.config.get(
"linked_boards",
default=[b.id if b is not None else None for b in self.linked_boards],
)
]
identified_ports = [
self.serial_reader.get_port(identified_port["port"])
for identified_port in identified_ports
]
change = False
for identified_port in identified_ports:
board = identified_port.board
# skip if alreay linked
if board in self.linked_boards:
continue
# link all already proposed boards
for i in range(len(proposed_linked_boards)):
if self.linked_boards[i] is not None:
continue
if proposed_linked_boards[i] == board.id:
self.link_board(i, board)
change = True
# link to free boards
for i in range(len(self.required_boards)):
if board.__class__ == self.required_boards[i]:
if board not in self.possible_boards[i]:
self.possible_boards[i].append(board)
change = True
# if already linked skip
if self.linked_boards[i] is not None:
continue
# if already reserved for another board
if proposed_linked_boards[i] is not None:
continue
# if matching board
self.link_board(i, board)
change = True
# unlink unavailable ports
for i in range(len(self.linked_boards)):
if self.linked_boards[i] is not None:
if self.linked_boards[i].serial_port not in identified_ports:
self.unlink_board(i)
change = True
if change:
for target in self._ws_targets:
target.send_boards(self)
def link_possible_board(self, index, possible_index):
try:
self.link_board(index, self.possible_boards[index][possible_index])
except Exception as e:
self.logger.exception(e)
def link_board(self, i, board):
"""
:param i: int
:type board: ArduinoBoard
"""
assert (
board.__class__ == self.required_boards[i]
), "the board you try o link({}) is not of the required type ({})".format(
board, self.required_boards[i]
)
if board is None:
return self.unlink_board(i)
linked_boards = self.config.get(
"linked_boards",
default=[b.id if b is not None else None for b in self.linked_boards],
)
linked_boards[i] = board.id
self.linked_boards[i] = board
board.get_serial_port().add_data_target(self)
self.logger.info(
"link board {}({}) to index {}".format(
board.id, board.__class__.__name__, i
)
)
self.config.put("linked_boards", value=linked_boards)
def unlink_board(self, i):
linked_boards = self.config.get(
"linked_boards",
default=[b.id if b is not None else None for b in self.linked_boards],
)
board = self.linked_boards[i]
if board is None:
return
linked_boards[i] = None
self.linked_boards[i] = None
board.get_serial_port().remove_data_target(self)
self.logger.info("unlink board from index {}".format(i))
self.config.put("linked_boards", value=linked_boards)
# remove from board possibilities
for i in range(len(self.possible_boards)):
if board in self.possible_boards[i]:
self.possible_boards[i].remove(board)
def get_possibilities_index(self, i):
return self.possible_boards[i]
def get_possibilities_board_class(self, board_class):
for i in range(len(self.required_boards)):
if board_class == self.required_boards[i]:
return self.get_possibilities_index(i)
return []
def get_possibilities_board(self, board):
return self.get_possibilities_board_class(board.__class__)
get_board_alternatives = get_possibilities_board
def add_ws_target(self, receiver):
self._ws_targets.add(receiver)
def pause_run(self):
self.pause = True
def continue_run(self):
self.pause = False
def stop_run(self):
self.running = False
self.pause = False
for func in self._on_stop_functions:
func()
def on_stop(self, func):
self._on_stop_functions.append(func)
def remove_ws_target(self, receiver):
if receiver in self._ws_targets:
self._ws_targets.remove(receiver)
def get_boards(self):
return dict(
required_boards=[b.__name__ for b in self.required_boards],
possible_boards=self.possible_boards,
linked_boards=[
{"board": board, "id": board.id} if board is not None else None
for board in self.linked_boards
],
)
def get_status(self):
if None in self.linked_boards:
return dict(status=False, reason=self.STATUS[1], code=1)
if self.pause:
return dict(status=False, reason=self.STATUS[3], code=3)
if self.running:
return dict(status=False, reason=self.STATUS[2], code=2)
return dict(status=True, reason=self.STATUS[0], code=0)
def get_data(self):
for linked_board in self.linked_boards:
for key, item in linked_board.get_all_variable_values().items():
self.port_data_point(
key=key,
x=None,
y=item,
port=linked_board.port,
board=linked_board.id,
)
return self._data
def get_running_data(self):
if not self.running:
return None
return self.data_logger.get_serializable_data()
def get_functions(self):
functions = {}
for method in dir(self):
try:
m = getattr(self, method)
if m.api_function:
functions[method] = m.__dict__
except AttributeError:
pass
return functions
class ArduinoAPIWebsocketConsumer:
apis = list()
active_consumer = None
logger = logging.getLogger("ArduinoAPIWebsocketConsumer")
reset_time = 3
accepting = True
BROADCASTING_TIME = 3
def __init__(self):
self.broadcasting = False
self.broadcast_time = self.BROADCASTING_TIME
@classmethod
def register_api(cls, api):
"""
:type api: BoardApi
"""
if api not in cls.apis:
cls.apis.append(api)
if cls.active_consumer is not None:
if api not in cls.active_consumer.apis:
cls.active_consumer.apis.append(api)
api.add_ws_target(cls.active_consumer)
cls.active_consumer.to_client(
dict(cmd="set_apis", data=cls.active_consumer.get_apis()),
type="cmd",
)
@classmethod
def register_at_apis(cls, receiver):
if not cls.accepting:
return False
cls.accepting = False
if cls.active_consumer is not None:
t = time.time()
cls.active_consumer.status = False
try:
while (
cls.active_consumer.status is False
and time.time() - t < cls.reset_time
):
cls.active_consumer.to_client(dict(cmd="get_status"), type="cmd")
time.sleep(0.5)
if cls.active_consumer.status is False:
cls.active_consumer.to_client(
data=dict(cmd="error", message="client did not respond"),
type="cmd",
)
cls.active_consumer.close_api_reciever()
cls.active_consumer = None
cls.accepting = True
return False
except:
return cls.register_at_apis(receiver)
else:
cls.active_consumer = receiver
for api in cls.apis:
api.add_ws_target(receiver)
cls.accepting = True
return True
@classmethod
def unregister_at_apis(cls, receiver):
try:
cls.instances.remove(receiver)
except:
pass
for api in cls.apis:
api.remove_ws_target(receiver)
cls.active_consumer = None
def client_to_api(self, textdata):
data = json.loads(textdata)
try:
if data["type"] == "cmd":
self.parse_command(data["data"])
else:
raise ValueError("invalid type: {} ".format(data["type"]))
except Exception as e:
self.logger.exception(e)
def close(self):
self.unregister_at_apis(self)
def parse_command(self, data):
if hasattr(self, data["cmd"]) and not "api" in data["data"]:
answer = filter_dict.call_method(
getattr(self, data["cmd"]), kwargs=data["data"]
)
else:
api = data["data"]["api"]
del data["data"]["api"]
answer = filter_dict.call_method(
getattr(self.apis[api], data["cmd"]), kwargs=data["data"]
)
if answer is not None:
if not isinstance(answer, dict):
answer = {"data": answer}
answer["api_position"] = api
if answer is not None:
self.to_client(
dict(cmd=data["cmd"].replace("get_", "set_"), data=answer), type="cmd"
)
def get_apis(self):
return self.apis
def send_boards(self, api):
data = api.get_boards()
data["api_position"] = self.apis.index(api)
self.to_client(dict(cmd="set_boards", data=data), type="cmd")
def to_client(self, data=None, type=None):
raise AttributeError("no valid to_client function implemented")
def get_status(self):
return [self.apis[i].get_status() for i in range(len(self.apis))]
def get_data(self):
return [self.apis[i].get_data() for i in range(len(self.apis))]
def get_running_data(self):
return [self.apis[i].get_running_data() for i in range(len(self.apis))]
def broadcast_status(self):
try:
stati = self.get_status()
if 2 in [status["code"] for status in stati]:
self.broadcast_time = min(1, self.broadcast_time)
self.to_client(dict(cmd="set_status", data=stati), type="cmd")
except:
pass
def broadcast_data(self):
self.to_client(dict(cmd="set_data", data=self.get_data()), type="cmd")
def broadcast_running_data(self):
rd = self.get_running_data()
for d in rd:
if d is not None:
return self.to_client(
dict(cmd="set_running_data", data=self.get_running_data()),
type="cmd",
)
def broadcast(self):
while self.broadcasting:
try:
self.broadcast_time = self.BROADCASTING_TIME
self.broadcast_status()
self.broadcast_data()
self.broadcast_running_data()
except:
pass
time.sleep(self.broadcast_time)
def close_api_reciever(self):
self.broadcasting = False
self.unregister_at_apis(self)
def start_broadcast(self):
self.broadcasting = True
threading.Thread(target=self.broadcast).start()
|
ArduinoController
|
/ArduinoController-0.1.1568726333.tar.gz/ArduinoController-0.1.1568726333/arduino_controller/board_api.py
|
board_api.py
|
import glob
import importlib.util
import inspect
import os
from os.path import basename
BOARDS = {}
BOARD_SOURCES = []
class BoardSource:
def __init__(self, prefix=""):
self.prefix = prefix
def board_by_firmware(self, firmware):
pass
class PathBoardSource(BoardSource):
def __init__(self, path, prefix=""):
super().__init__(prefix)
self.path = path
def board_by_firmware(self, firmware):
self._find_boards()
return BOARDS.get(firmware, None)
def _find_boards(self, path=None, prefix=None):
if path is None:
path = self.path
if prefix is None:
prefix = self.prefix
boardsfolders = [
p
for p in glob.glob(path + "/*")
if os.path.isdir(p) and not p.endswith("__")
]
prefix = prefix + os.path.basename(path) + "."
for boardfolder in boardsfolders:
boardpy = os.path.join(boardfolder, "board.py")
if os.path.exists(boardpy):
spec = importlib.util.spec_from_file_location(
"_board." + prefix + basename(boardfolder),
os.path.join(boardfolder, "board.py"),
)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
for name, obj in inspect.getmembers(foo):
if inspect.isclass(obj):
try:
add_board(obj)
except:
pass
else:
self._find_boards(boardfolder, prefix)
class WebBoardSource(PathBoardSource):
def __init__(self, download_path, by_firmware_request, prefix="downloaded"):
super().__init__(path=download_path, prefix=prefix)
self.by_firmware_request = by_firmware_request
def board_by_firmware(self, firmware):
# webrequest
import zipfile
import requests
import io
response = requests.get(
self.by_firmware_request.format(firmware), allow_redirects=True
)
with zipfile.ZipFile(io.BytesIO(response.content)) as zip_ref:
zip_ref.extractall(self.path)
super().board_by_firmware(firmware)
def board_by_firmware(firmware):
board = BOARDS.get(firmware, None)
for source in BOARD_SOURCES:
board = source.board_by_firmware(firmware)
if board is not None:
return board
return board
def parse_path_for_boards(path, prefix=""):
global BOARD_SOURCES
BOARD_SOURCES.append(PathBoardSource(path, prefix=prefix))
def add_board(board_class):
global BOARDS
if board_class.FIRMWARE not in BOARDS:
BOARDS[board_class.FIRMWARE] = {
"firmware": board_class.FIRMWARE,
"classcaller": board_class,
"name": board_class.CLASSNAME,
}
|
ArduinoController
|
/ArduinoController-0.1.1568726333.tar.gz/ArduinoController-0.1.1568726333/arduino_controller/parseboards.py
|
parseboards.py
|
import logging
import logging
import time
from ArduinoCodeCreator import basic_types as at
from ArduinoCodeCreator.arduino import Eeprom, Serial, Arduino
from ArduinoCodeCreator.arduino_data_types import *
from ArduinoCodeCreator.code_creator import ArduinoCodeCreator
from ArduinoCodeCreator.statements import (
for_,
if_,
return_,
while_,
continue_,
else_,
elseif_,
)
from arduino_controller.modul_variable import ModuleVariableTemplate, ModuleVariable
from arduino_controller.portcommand import PortCommand
from arduino_controller.python_variable import PythonVariable
MAXATTEMPTS = 3
IDENTIFYTIME = 2
_GET_PREFIX = "get_"
_SET_PREFIX = "set_"
COMMAND_FUNCTION_COMMUNICATION_ARGUMENTS = [
at.Array("data", uint8_t, 0),
at.Variable(type=uint8_t, name="s"),
]
WRITE_DATA_FUNCTION = at.Function(
"write_data", ((T, "data"), (uint8_t, "cmd")), template_void
)
from arduino_controller.arduino_variable import arduio_variable, ArduinoVariable
class ArduinoBoard:
modules = []
FIRMWARE = -1
BAUD = 9600
CLASSNAME = None
def __init__(self):
if self.CLASSNAME is None:
self.CLASSNAME = self.__class__.__name__
self._first_free_byte_id = 0
self._serial_port = None
self._port = None
self._logger = logging.getLogger("Unidentified " + self.__class__.__name__)
self.name = None
self._last_data = None
self._update_time = 2
self._identify_attempts = 0
self.identified = False
self.id = None
self.port_commands = []
self.id = None
self._loaded_module_instances = []
self._module_variables = {}
self.eeprom_position = at.ArduinoEnum("eeprom_position", {})
self.byte_ids = at.ArduinoEnum("byte_ids", {})
for module in self.modules:
self.load_module(module)
# print(self._loaded_module_instances)
self.initalize_variables()
for module in self._loaded_module_instances:
module.post_initalization()
for attr, ard_var in self._module_variables.items():
if isinstance(ard_var, ArduinoVariable):
if ard_var.arduino_setter is not None:
self.add_port_command(
PortCommand(
module=self,
name=_SET_PREFIX + ard_var.name,
python_sendtype=ard_var.type.python_type,
python_receivetype=None,
receivefunction=ard_var.set_without_sending_to_board,
arduino_function=ard_var.arduino_setter,
)
)
if ard_var.arduino_getter is not None:
self.add_port_command(
PortCommand(
module=self,
name=_GET_PREFIX + ard_var.name,
python_sendtype=None,
python_receivetype=ard_var.type.python_type,
receivefunction=ard_var.set_without_sending_to_board,
arduino_function=ard_var.arduino_getter,
)
)
for attr, modvar in self._module_variables.items():
modvar.return_self = False
def create_ino(self, file=None, obscure=False):
arduino_code_creator = ArduinoCodeCreator()
assert self.FIRMWARE > -1, "No Firmware defined"
# self.firmware = self.FIRMWARE
for attr, modvar in self._module_variables.items():
modvar.return_self = True
self.firmware.value = self.FIRMWARE
module_classes = []
for module in self._loaded_module_instances:
if module.__class__ not in module_classes:
module_classes.append(module.__class__)
for module_class in module_classes:
module_class._module_arduino_code(self, arduino_code_creator)
module_class.module_arduino_code(self, arduino_code_creator)
for module in self._loaded_module_instances:
module._instance_arduino_code(arduino_code_creator)
module.instance_arduino_code(arduino_code_creator)
ino = arduino_code_creator.create_code(obscure=obscure)
if file is None:
print(ino)
return
with open(file, "w+") as f:
f.write(ino)
def initalize_variables(self):
for module in self._loaded_module_instances:
for attribute, tempplate in module.module_variable_templates.items():
tempplate.original_name = attribute
i = 0
while tempplate.name in self._module_variables:
i += 1
tempplate.name = "{}_{}".format(attribute, i)
self._module_variables[tempplate.name] = tempplate.initialize(
self, tempplate.name
)
setattr(module, attribute, self._module_variables[tempplate.name])
# print(self._module_variables)
def load_module(self, module):
"""
:type module: ArduinoBoardModule
"""
module_instance = module.get_instance(self)
if module_instance in self._loaded_module_instances:
return module_instance
for name, submodule in module_instance.get_dependencies().items():
setattr(module_instance, name, self.load_module(submodule))
if module_instance in self._loaded_module_instances:
return module_instance
self._loaded_module_instances.append(module_instance)
return module_instance
def set_update_time(self, update_time):
self._update_time = update_time
def get_update_time(self):
return self._update_time
update_time = property(get_update_time, set_update_time)
def set_serial_port(self, serialport):
self._serial_port = serialport
self._logger = serialport.logger
if self.name is None or self.name == self._port:
self.name = serialport.port
self._port = serialport.port
def get_serial_port(self):
return self._serial_port
def get_port(self):
return self._port
serial_port = property(get_serial_port, set_serial_port)
port = property(get_port)
def get_portcommand_by_name(self, command_name):
for p in self.port_commands:
if p.name == command_name:
return p
return None
def identify(self):
from arduino_controller.serialport import BAUDRATES
for b in set([self._serial_port.baudrate] + list(BAUDRATES)):
self._identify_attempts = 0
self._logger.info(
"intentify with baud " + str(b) + " and firmware " + str(self.FIRMWARE)
)
try:
self._serial_port.baudrate = b
while self.id is None and self._identify_attempts < MAXATTEMPTS:
self.get_portcommand_by_name("identify").sendfunction(0)
self._identify_attempts += 1
time.sleep(IDENTIFYTIME)
if self.id is not None:
self.identified = True
break
except Exception as e:
self._logger.exception(e)
if not self.identified:
return False
self.identified = False
self._identify_attempts = 0
while self.firmware == -1 and self._identify_attempts < MAXATTEMPTS:
self.get_portcommand_by_name(_GET_PREFIX + "firmware").sendfunction()
self._identify_attempts += 1
time.sleep(IDENTIFYTIME)
if self.firmware > -1:
self.identified = True
return self.identified
def get_first_free_byte_id(self):
ffbid = self._first_free_byte_id
self._first_free_byte_id += 1
return ffbid
first_free_byte_id = property(get_first_free_byte_id)
def get_portcommand_by_cmd(self, byteid):
for p in self.port_commands:
if p.byteid == byteid:
return p
return None
def add_port_command(self, port_command):
assert (
self.get_portcommand_by_cmd(port_command.byteid) is None
and self.get_portcommand_by_name(port_command.name) is None
), "byteid of {} {} already defined".format(port_command, port_command.name)
self.port_commands.append(port_command)
return port_command
def get_module_vars(self):
return self._module_variables
def get_arduino_vars(self):
return {
attr: ard_var
for attr, ard_var in self.get_module_vars().items()
if isinstance(ard_var, ArduinoVariable)
}
def get_python_vars(self):
return {
attr: ard_var
for attr, ard_var in self.get_module_vars().items()
if isinstance(ard_var, PythonVariable)
}
def receive_from_port(self, cmd, data):
self._logger.debug(
"receive from port cmd: " + str(cmd) + " " + str([i for i in data])
)
portcommand = self.get_portcommand_by_cmd(cmd)
if portcommand is not None:
portcommand.receive(data)
else:
self._logger.debug("cmd " + str(cmd) + " not defined")
def get_portcommand_arduino_getter(self, arduino_getter):
if arduino_getter is None:
return None
for p in self.port_commands:
if p.arduino_function is arduino_getter:
return p
return None
def data_point(self, name, data):
self._last_data = data
if self.identified:
self._serial_port.add_data_point(self, str(name), y=data, x=None)
def restore(self, data):
for attr, ard_var in self.get_arduino_vars().items():
# print(attr)
if ard_var.arduino_getter:
pc = self.get_portcommand_arduino_getter(ard_var.arduino_getter)
if pc is not None:
if pc is not None:
pc.sendfunction(0)
time.sleep(1)
for attr, ard_var in self.get_module_vars().items():
if ard_var.save and attr in data:
setattr(self, attr, data[attr])
# print(attr, self.get_portcommand_arduino_getter(ard_var.arduino_getter))
def get_all_variable_values(self):
data = {}
for attr, py_var in self.get_module_vars().items():
data[attr] = py_var.value
return data
def save(self):
data = {}
for attr, py_var in self.get_module_vars().items():
if py_var.save:
data[attr] = py_var.value
return data
def get_board(self):
board = {"module_variables": {}}
for attr, mod_var in self.get_module_vars().items():
if len(mod_var.html_input) > 0:
form = mod_var.html_input.replace(
"{{value}}", str(getattr(self, attr, ""))
)
board["module_variables"][attr] = {"form": form}
return board
def __getattribute__(self, attr):
obj = object.__getattribute__(self, attr)
if isinstance(obj, ModuleVariable):
obj = obj.get_value(self, type(self))
return obj
def __setattr__(self, attr, value):
obj = None
if hasattr(self, attr):
obj = object.__getattribute__(self, attr)
if isinstance(obj, ModuleVariable):
obj = obj.set_value(self, value)
else:
object.__setattr__(self, attr, value)
def __repr__(self):
return "{}({})".format(self.CLASSNAME, self.id)
class ArduinoBoardModule:
unique = False
_instances = []
def post_initalization(self):
pass
def __getattribute__(self, attr):
obj = object.__getattribute__(self, attr)
if isinstance(obj, ModuleVariable):
obj = obj.get_value(self, type(self))
return obj
def __setattr__(self, attr, value):
obj = None
if hasattr(self, attr):
obj = object.__getattribute__(self, attr)
if isinstance(obj, ModuleVariable):
obj = obj.set_value(self, value)
else:
object.__setattr__(self, attr, value)
@classmethod
def add_ardvar_to_board(cls, variable, board, arduino_code_creator):
if variable.is_data_point:
BasicBoardModule.dataloop.add_call(
WRITE_DATA_FUNCTION(
variable,
board.byte_ids.get(
board.get_portcommand_by_name(
_GET_PREFIX + variable.name
).arduino_function
),
)
)
if variable.eeprom:
board.eeprom_position.add_possibility(
variable, size=variable.type.byte_size
)
arduino_code_creator.setup.prepend_call(
Eeprom.get(board.eeprom_position.get(variable), variable)
)
@classmethod
def _arduino_code_try_to_add_var(cls, variable, board, arduino_code_creator):
if isinstance(variable, at.Variable):
if getattr(variable, "add_to_code", True):
arduino_code_creator.add(variable)
if isinstance(variable, ArduinoVariable):
cls.add_ardvar_to_board(variable, board, arduino_code_creator)
if isinstance(variable, at.Function):
arduino_code_creator.add(variable)
if isinstance(variable, at.ArduinoEnum):
arduino_code_creator.add(variable)
if isinstance(variable, at.ArduinoClass):
arduino_code_creator.add(variable)
if isinstance(variable, at.Definition):
arduino_code_creator.add(variable)
if isinstance(variable, at.Include):
arduino_code_creator.add(variable)
@classmethod
def _module_arduino_code(cls, board, arduino_code_creator):
for name, variable in cls.__dict__.items():
cls._arduino_code_try_to_add_var(variable, board, arduino_code_creator)
def _instance_arduino_code(self, arduino_code_creator):
for name, variable in self.__dict__.items():
# print(name,variable.__class__)
self._arduino_code_try_to_add_var(
variable, self.board, arduino_code_creator
)
@classmethod
def module_arduino_code(cls, board, arduino_code_creator):
pass
def instance_arduino_code(self, arduino_code_creator):
pass
def __repr__(self):
return "{}:{}".format(self.__class__.__name__, id(self))
def get_dependencies(self):
depencies = {}
for name, dependency in self.__class__.__dict__.items():
try:
if issubclass(dependency, ArduinoBoardModule):
depencies[name] = dependency
except TypeError:
pass
return depencies
def __init__(self, board):
self.board = board
self._instances.append(self)
self.module_variable_templates = {}
self._load_module_variable_templates()
def _load_module_variable_templates(self):
for name, module_variable in self.__class__.__dict__.items():
try:
if isinstance(module_variable, ModuleVariableTemplate):
self.module_variable_templates[name] = module_variable
except TypeError:
pass
@classmethod
def get_instance(cls, board, *args, **kwargs):
initiate = None
if cls.unique:
for instance in cls._instances:
if instance.board is board and cls is instance.__class__:
return instance
return cls(board)
class ArduinoBoard2:
FIRMWARE = -1
CLASSNAME = None
BAUD = 9600
modules = []
def __init__(self):
self._module_variables = {}
# self.eeprom_position = at.ArduinoEnum("eeprom_position", {})
# self.byte_ids = at.ArduinoEnum("byte_ids", {})
self.loaded_module_instances = []
# for module in self.modules:
# self.load_module(module)
self.initialize_variables()
for module in self.loaded_module_instances:
module.after_added_to_board(board=self)
for attr, modvar in self._module_variables.items():
modvar.return_self = False
def initialize_variables(self):
for module in self.loaded_module_instances:
for module_variable in module.get_module_variables():
i = 0
prename = module_variable.name
set_name = module_variable.name
while hasattr(self, set_name):
i += 1
set_name = "{}_{}".format(module_variable.name, i)
variable_instance = module_variable.initialize(self, set_name)
# print(module, prename, variable_instance)
setattr(module, prename, variable_instance)
setattr(module, set_name, variable_instance)
self._module_variables[set_name] = variable_instance
class ArduinoBoardModule2:
unique = False
_last_instance = None
def after_added_to_board(self, board):
pass
def __getattribute__(self, attr):
obj = object.__getattribute__(self, attr)
if isinstance(obj, ModuleVariable):
obj = obj.get_value(self, type(self))
return obj
def __setattr__(self, attr, value):
obj = None
if hasattr(self, attr):
obj = object.__getattribute__(self, attr)
if isinstance(obj, ModuleVariable):
if not obj.return_self:
obj.set_value(self, value)
return
object.__setattr__(self, attr, value)
# @classmethod
# def _arduino_code_try_to_add_var(cls,variable, board,arduino_code_creator):
# if isinstance(variable, at.Variable):
# if getattr(variable, "add_to_code", True):
# arduino_code_creator.add(variable)
#
# if isinstance(variable, ArduinoVariable):
# cls.add_ardvar_to_board(variable, board, arduino_code_creator)
#
# if isinstance(variable, at.Function):
# arduino_code_creator.add(variable)
#
# if isinstance(variable, at.ArduinoEnum):
# arduino_code_creator.add(variable)
#
# if isinstance(variable, at.ArduinoClass):
# arduino_code_creator.add(variable)
#
# if isinstance(variable, at.Definition):
# arduino_code_creator.add(variable)
# @classmethod
# def _module_arduino_code(cls, board, arduino_code_creator):
# for name, variable in cls.__dict__.items():
# cls._arduino_code_try_to_add_var(variable,board,arduino_code_creator)
#
# def _instance_arduino_code(self, board, arduino_code_creator):
# for name, variable in self.__dict__.items():
# # print(name,variable.__class__)
# self._arduino_code_try_to_add_var(variable,board,arduino_code_creator)
#
#
# @classmethod
# def module_arduino_code(cls, board, arduino_code_creator):
# pass
#
# def instance_arduino_code(self, board, arduino_code_creator):
# pass
def __init__(self):
self._dependencies = []
self._module_variables = []
self.load_dependencies()
self.load_module_variables()
# @classmethod
# def get_instance(cls, *args, **kwargs):
# if not cls.unique or cls._last_instance is None:
# cls._last_instance = cls(*args, **kwargs)
# return cls._last_instance
# def load_dependencies(self):
# for name, dependency in self.__class__.__dict__.items():
# try:
# if issubclass(dependency, ArduinoBoardModule):
# dependency = dependency.get_instance()
# if dependency not in self._dependencies:
# self._dependencies.append(dependency)
# setattr(self, name, dependency)
# except TypeError:
# pass
# def load_module_variables(self):
# for name, module_variable in self.__class__.__dict__.items():
# try:
# if isinstance(module_variable, ModuleVariableTemplate):
# self._module_variables.append(module_variable)
# except TypeError:
# pass
def get_module_variables(self, deep=False):
mv = []
if deep:
for dependency in self._dependencies:
for v in dependency.get_module_variables(deep=True):
if v not in mv:
mv.append(v)
for v in self._module_variables:
v._module_instance = self
if v not in mv:
mv.append(v)
return mv
def get_dependencies(self, deep=False):
if not deep:
dependencies = self._dependencies
else:
dependencies = []
for dependency in self._dependencies:
dependencies.extend(dependency.get_dependencies(deep=True))
dependencies.extend(self._dependencies)
seen = set()
seen_add = seen.add
return [x for x in dependencies if not (x in seen or seen_add(x))]
# @classmethod
# def add_ardvar_to_board(cls, variable, board, arduino_code_creator):
# if variable.is_data_point:
# BasicBoardModule.dataloop.add_call(
# WRITE_DATA_FUNCTION(
# variable, board.byte_ids.get(board.get_portcommand_by_name(_GET_PREFIX + variable.name).arduino_function)
# )
# )
# if variable.eeprom:
# board.eeprom_position.add_possibility(variable, size=variable.type.byte_size)
# arduino_code_creator.setup.prepend_call(Eeprom.get(board.eeprom_position.get(variable), variable))
from arduino_controller.portrequest import (
STARTBYTE,
DATABYTEPOSITION,
LENBYTEPOSITION,
STARTBYTEPOSITION,
COMMANDBYTEPOSITION,
)
class BasicBoardModule(ArduinoBoardModule):
unique = True
firmware = arduio_variable(
name="firmware",
arduino_data_type=uint64_t,
arduino_setter=False,
default=-1,
save=False,
unique=True,
)
arduino_id = arduio_variable(
arduino_data_type=uint64_t,
name="arduino_id",
eeprom=True,
getter=False,
setter=False,
arduino_setter=False,
arduino_getter=False,
)
arduino_id_cs = arduio_variable(
arduino_data_type=uint16_t,
name="arduino_id_cs",
eeprom=True,
getter=False,
setter=False,
arduino_setter=False,
arduino_getter=False,
)
data_rate = arduio_variable(
name="data_rate", arduino_data_type=uint32_t, minimum=1, eeprom=True
)
dummy8 = at.Variable("dummy8", type=uint8_t)
dummy16 = at.Variable("dummy16", type=uint16_t)
dummy32 = at.Variable("dummy32", type=uint32_t)
dummy64 = at.Variable("dummy64", type=uint64_t)
STARTANALOG = at.Definition("STARTANALOG", 0)
STARTBYTE = at.Definition("STARTBYTE", int.from_bytes(STARTBYTE, "big"))
STARTBYTEPOSITION = at.Definition("STARTBYTEPOSITION", STARTBYTEPOSITION)
COMMANDBYTEPOSITION = at.Definition("COMMANDBYTEPOSITION", COMMANDBYTEPOSITION)
LENBYTEPOSITION = at.Definition("LENBYTEPOSITION", LENBYTEPOSITION)
ENDANALOG = at.Definition("ENDANALOG", 100)
MAXFUNCTIONS = at.Definition("MAXFUNCTIONS", 0)
BAUD = at.Definition("BAUD", 0)
DATABYTEPOSITION = at.Definition("DATABYTEPOSITION", DATABYTEPOSITION)
SERIALARRAYSIZE = at.Definition("SERIALARRAYSIZE", DATABYTEPOSITION + 2)
dataloop = at.Function("dataloop")
arduino_identified = at.Variable(type=bool_, value=0, name="arduino_identified")
current_time = at.Variable(type=uint32_t, name="current_time")
last_time = at.Variable(type=uint32_t, name="last_time")
def post_initalization(self):
def _receive_id(board, data):
board.id = np.uint64(data)
identify_portcommand = PortCommand(
module=self.board,
name="identify",
python_receivetype=np.uint64,
python_sendtype=np.bool,
receivefunction=_receive_id,
arduino_function=at.Function(
return_type=void,
arguments=COMMAND_FUNCTION_COMMUNICATION_ARGUMENTS,
name="identify",
code=(
self.arduino_identified.set(
COMMAND_FUNCTION_COMMUNICATION_ARGUMENTS[0][0]
),
),
),
)
identify_portcommand.arduino_function.add_call(
WRITE_DATA_FUNCTION(
self.arduino_id,
self.board.byte_ids.get(identify_portcommand.arduino_function),
)
)
self.board.add_port_command(identify_portcommand)
def instance_arduino_code(self, ad):
self.MAXFUNCTIONS.value = len(self.board.port_commands)
self.BAUD.value = self.board.BAUD
self.SERIALARRAYSIZE.value = (
DATABYTEPOSITION
+ max(
*[
max(portcommand.receivelength, portcommand.sendlength)
for portcommand in self.board.port_commands
],
0,
0
)
+ 2
)
ad.add(self.board.eeprom_position)
ad.add(self.board.byte_ids)
last_data = ad.add(at.Variable("lastdata", uint32_t, 0))
current_character = ad.add(at.Variable(type=uint8_t, name="current_character"))
checksum = ad.add(at.Variable(type=uint16_t, name="checksum"))
serialreadpos = ad.add(at.Variable(type=uint8_t, value=0, name="serialreadpos"))
commandlength = ad.add(at.Variable(type=uint8_t, value=0, name="commandlength"))
writedata = ad.add(
at.Array(size=self.SERIALARRAYSIZE, type=uint8_t, name="writedata")
)
serialread = ad.add(
at.Array(size=self.SERIALARRAYSIZE, type=uint8_t, name="serialread")
)
cmds = ad.add(at.Array(size=self.MAXFUNCTIONS, type=uint8_t, name="cmds"))
cmd_length = ad.add(
at.Array(size=self.MAXFUNCTIONS, type=uint8_t, name="cmd_length")
)
cmd_calls = ad.add(
at.FunctionArray(
size=self.MAXFUNCTIONS,
return_type=void,
arguments=COMMAND_FUNCTION_COMMUNICATION_ARGUMENTS,
name="cmd_calls",
)
)
ad.add(Eeprom)
i = for_.i
generate_checksum = ad.add(
at.Function(
"generate_checksum",
[at.Array("data"), (uint8_t, "count")],
variables=[(uint8_t, "sum1", 0), (uint8_t, "sum2", 0)],
)
)
generate_checksum.add_call(
# count_vaiable,endcondition,raising_value=1
for_(
i,
i < generate_checksum.arg2,
code=(
generate_checksum.var1.set(
generate_checksum.var1 + generate_checksum.arg1[i]
),
generate_checksum.var2.set(
generate_checksum.var1 + generate_checksum.var2
),
),
),
checksum.set(
generate_checksum.var2.cast(uint16_t) * 256 + generate_checksum.var1
),
)
write_data_array = ad.add(
at.Function(
"write_data_array",
[at.Array("data"), (uint8_t, "cmd"), (uint8_t, "len")],
void,
)
)
write_data_array.add_call(
writedata[self.STARTBYTEPOSITION].set(self.STARTBYTE),
writedata[self.COMMANDBYTEPOSITION].set(write_data_array.arg2),
writedata[self.LENBYTEPOSITION].set(write_data_array.arg3),
for_(
i,
i < write_data_array.arg3,
1,
writedata[self.DATABYTEPOSITION + i].set(write_data_array.arg1[i]),
),
generate_checksum(writedata, write_data_array.arg3 + self.DATABYTEPOSITION),
writedata[self.DATABYTEPOSITION + write_data_array.arg3].set(checksum >> 0),
writedata[self.DATABYTEPOSITION + write_data_array.arg3 + 1].set(
checksum >> 8
),
Serial.write_buf(
writedata, self.DATABYTEPOSITION + write_data_array.arg3 + 2
),
)
write_data_function = ad.add(WRITE_DATA_FUNCTION)
# d = write_data_function.add_variable(
# at.Array(size=Arduino.sizeof(T), type=uint8_t, name="d")
# )
write_data_function.add_call(
# for_(
# i,
# i < Arduino.sizeof(T),
# 1,
# d[i].set((write_data_function.arg1 >> i * 8 & 0xFF).cast(uint8_t)),
# ),
write_data_array(
write_data_function.arg1.to_pointer(),
write_data_function.arg2,
Arduino.sizeof(T),
)
)
check_uuid = ad.add(
at.Function(
"check_uuid", return_type=void, variables=[(checksum.type, "id_cs")]
)
)
checkuuidvar = at.Variable(
"i", uint8_t, self.board.eeprom_position.get(self.arduino_id)
)
check_uuid.add_call(
generate_checksum(
self.arduino_id.to_pointer(), Arduino.sizeof(self.arduino_id)
),
Eeprom.get(Arduino.sizeof(self.arduino_id), check_uuid.var1),
if_(
checksum != check_uuid.var1,
code=(
for_(
checkuuidvar,
checkuuidvar < Arduino.sizeof(self.arduino_id),
1,
Eeprom.write(i, Arduino.random()),
),
Eeprom.get(
self.board.eeprom_position.get(self.arduino_id), self.arduino_id
),
generate_checksum(
self.arduino_id.to_pointer(), Arduino.sizeof(self.arduino_id)
),
Eeprom.put(
self.board.eeprom_position.get(self.arduino_id_cs), checksum
),
),
),
)
add_command = ad.add(
at.Function(
return_type=void,
arguments=[
(uint8_t, "cmd"),
(uint8_t, "len"),
at.Function(
return_type=void,
arguments=[(uint8_t_pointer, "data"), (uint8_t, "s")],
name="caller",
),
],
name="add_command",
)
)
add_command.add_call(
for_(
i,
i < self.MAXFUNCTIONS,
1,
if_(
cmds[i] == 255,
code=(
cmds[i].set(add_command.arg1),
cmd_length[i].set(add_command.arg2),
cmd_calls[i].set(add_command.arg3),
return_(),
),
),
)
)
endread = ad.add(at.Function("endread"))
endread.add_call(commandlength.set(0), serialreadpos.set(0))
get_cmd_index = ad.add(
at.Function("get_cmd_index", [(uint8_t, "cmd")], uint8_t)
)
get_cmd_index.add_call(
for_(
i,
i < self.MAXFUNCTIONS,
1,
if_(cmds[i] == get_cmd_index.arg1, return_(i)),
),
return_(255),
)
validate_serial_command = ad.add(
at.Function(
"validate_serial_command",
variables=[
(uint8_t, "cmd_index"),
at.Array(size=serialread[LENBYTEPOSITION], name="data"),
],
)
)
validate_serial_command.add_call(
generate_checksum(
serialread, self.DATABYTEPOSITION + serialread[self.LENBYTEPOSITION]
),
if_(
checksum
== (
(
serialread[
self.DATABYTEPOSITION + serialread[self.LENBYTEPOSITION] + 1
]
).cast(uint16_t)
* 256
)
+ serialread[self.DATABYTEPOSITION + serialread[self.LENBYTEPOSITION]],
code=(
validate_serial_command.var1.set(
get_cmd_index(serialread[self.COMMANDBYTEPOSITION])
),
if_(
validate_serial_command.var1 != 255,
code=(
Arduino.memcpy(
validate_serial_command.var2,
serialread[self.DATABYTEPOSITION].to_pointer(),
serialread[self.LENBYTEPOSITION],
),
cmd_calls[validate_serial_command.var1](
validate_serial_command.var2,
serialread[self.LENBYTEPOSITION],
),
),
),
),
),
)
readloop = ad.add(
at.Function(
"readloop",
code=(
while_(
Serial.available() > 0,
code=(
if_(serialreadpos > self.SERIALARRAYSIZE, endread()),
current_character.set(Serial.read()),
serialread[serialreadpos].set(current_character),
if_(
serialreadpos == self.STARTBYTEPOSITION,
code=if_(
current_character != self.STARTBYTE,
code=(endread(), continue_()),
),
),
else_(
if_(
serialreadpos == self.LENBYTEPOSITION,
commandlength.set(current_character),
),
elseif_(
serialreadpos - commandlength
> self.DATABYTEPOSITION + 1,
code=(endread(), continue_()),
),
elseif_(
serialreadpos - commandlength
== self.DATABYTEPOSITION + 1,
code=(
validate_serial_command(),
endread(),
continue_(),
),
),
),
serialreadpos.set(serialreadpos + 1),
),
)
),
)
)
ad.loop.add_call(
readloop(),
self.last_time.set(self.current_time),
self.current_time.set(Arduino.millis()),
if_(
(self.current_time - last_data > self.board.data_rate).and_(
self.arduino_identified
),
code=(self.dataloop(), last_data.set(self.current_time)),
),
)
ti = at.Variable("i", int_, self.STARTANALOG)
ad.setup.add_call(
Serial.begin(self.BAUD),
# Eeprom.get(0, self.arduino_id),
for_(
ti,
ti < self.ENDANALOG,
1,
Arduino.randomSeed(
Arduino.max(1, Arduino.analogRead(ti)) * Arduino.random()
),
),
check_uuid(),
for_(i, i < self.MAXFUNCTIONS, 1, cmds[i].set(255)),
self.current_time.set(Arduino.millis()),
self.last_time.set(self.current_time),
*[
add_command(
self.board.byte_ids.get(portcommand.arduino_function),
portcommand.sendlength,
portcommand.arduino_function.name,
)
for portcommand in self.board.port_commands
]
)
for portcommand in self.board.port_commands:
# arduino_code_creator.add(BYTEID.redefine(portcommand.byteid))
ad.add(portcommand.arduino_function)
class BasicBoard(ArduinoBoard):
FIRMWARE = 0
modules = [BasicBoardModule]
if __name__ == "__main__":
ins = BasicBoard()
ins.create_ino()
|
ArduinoController
|
/ArduinoController-0.1.1568726333.tar.gz/ArduinoController-0.1.1568726333/arduino_controller/basicboard/board.py
|
board.py
|
import logging
import os
import threading
import time
import filter_dict
from json_dict import JsonDict
from ..serialreader import serialdetector
AUTO_CHECK_PORTS = True
PORT_CHECK_TIME = 2
DATAPOINT_RESOLUTION = 200
class SerialReaderDataTarget:
def __init__(self):
pass
def set_ports(
self, available_ports, ignored_ports, connected_ports, identified_ports
):
pass
def port_identified(self, port):
pass
def port_opened(self, port, baud):
pass
def port_closed(self, port):
pass
class SerialReader:
def __init__(
self,
auto_check_ports=AUTO_CHECK_PORTS,
port_check_time=PORT_CHECK_TIME,
start_in_background=False,
config: JsonDict = None,
logger=None,
permanently_ignored_ports=None,
# datalogger: DataLogger = None,
):
self.data_targets = set()
self.ignored_ports = set()
self.dead_ports = set()
self.connected_ports = set()
self.available_ports = set()
self.identified_ports = set()
self.running = False
self.read_thread = None
# self.datalogger = DataLogger() if datalogger is None else datalogger
self.config = (
JsonDict(
os.path.join(
os.path.expanduser("~"), ".arduino_controller", "portdata.json"
)
)
if config is None
else config
)
if permanently_ignored_ports is None:
permanently_ignored_ports = []
self.port_check_time = port_check_time
self.auto_check_ports = auto_check_ports
self.permanently_ignored_ports = set(permanently_ignored_ports)
# self.set_communicator(python_communicator.PythonCommunicator() if communicator is None else communicator)
self.logger = logging.getLogger("SerialReader") if logger is None else logger
if start_in_background:
self.run_in_background()
def get_identified_by_port(self, port):
for sp in self.identified_ports:
if sp.port == port:
return sp
return None
def run_in_background(self):
if self.read_thread is not None:
self.stop()
self.read_thread = threading.Thread(target=self.read_forever)
self.read_thread.start()
def reactivate_port(self, port=None):
if port is None:
return
try:
self.ignored_ports.remove(port)
except:
pass
try:
self.permanently_ignored_ports.remove(port)
except:
pass
try:
self.dead_ports.remove(port)
except:
pass
def deactivate_port(self, port=None):
if port is None:
return
self.ignored_ports.add(port)
self._communicator.cmd_out(targets=[port], cmd="stop_read")
# def set_communicator(self, communicator: python_communicator.PythonCommunicator):
# self._communicator = communicator
# self._communicator.add_node("serialreader", self)
# def get_communicator(self):
# return self._communicator
# communicator = property(get_communicator, set_communicator)
def add_data_target(self, data_target=None):
if data_target is not None:
self.data_targets.add(data_target)
def remove_data_target(self, data_target):
if data_target in self.data_targets:
self.data_targets.remove(data_target)
def send_ports(self, data_target=None):
if data_target is None:
data_target = self.data_targets
if not isinstance(data_target, set):
data_target = set(data_target)
for data_target in data_target:
filter_dict.call_method(
target=data_target.set_ports,
kwargs=dict(
available_ports=list(self.available_ports),
ignored_ports=list(
self.ignored_ports | self.permanently_ignored_ports
),
connected_ports=[
dict(port=sp.port, baudrate=sp.baudrate)
for sp in self.connected_ports
],
identified_ports=[
dict(port=sp.port, baudrate=sp.baudrate)
for sp in self.identified_ports
],
),
)
get_ports = send_ports
def stop(self):
self.running = False
if self.read_thread is not None:
self.read_thread.join(timeout=2*self.port_check_time)
self.read_thread = None
for port in self.connected_ports.union(self.identified_ports):
port.stop_read()
def read_forever(self):
self.running = True
while self.running:
if self.auto_check_ports:
self.available_ports, self.ignored_ports = serialdetector.get_avalable_serial_ports(
ignore=self.ignored_ports
| self.permanently_ignored_ports # | set(
# [sp.port for sp in self.connected_ports])
)
self.dead_ports = self.available_ports.intersection(self.dead_ports)
newports = self.available_ports - (
self.ignored_ports
| self.dead_ports
| self.permanently_ignored_ports
)
self.logger.debug(
"available Ports: "
+ str(self.available_ports)
+ "; new Ports: "
+ str(newports)
+ "; ignored Ports: "
+ str(self.ignored_ports | self.permanently_ignored_ports)
+ "; connected Ports: "
+ str([sp.port for sp in self.connected_ports])
+ "; identified Ports: "
+ str([sp.port for sp in self.identified_ports])
)
self.send_ports()
for port in newports.copy():
try:
self.open_port(port)
except Exception as e:
self.logger.exception(e)
pass
time.sleep(self.port_check_time)
def get_port(self, port):
for sp in self.identified_ports:
if sp.port == port:
return sp
for sp in self.connected_ports:
if sp.port == port:
return sp
return None
def open_port(self, port):
self.reactivate_port(port)
from ..serialport import open_serial_port
t = threading.Thread(
target=open_serial_port,
kwargs={
**{
"serial_reader": self,
"config": self.config,
"port": port,
"baudrate": self.config.get("portdata", port, "baud", default=9600),
}
},
)
t.start()
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
sr = SerialReader()
sr.read_forever()
|
ArduinoController
|
/ArduinoController-0.1.1568726333.tar.gz/ArduinoController-0.1.1568726333/arduino_controller/serialreader/serialreader.py
|
serialreader.py
|
from __future__ import unicode_literals
from __future__ import print_function
import os
import fnmatch
import glob
import CppHeaderParser
KEYWORDS_FILENAME = u"keywords.txt"
KEYWORD_SEP = u"\t"
KEYWORD_FORMAT_CLASS = u"{{class_name}}{separator}KEYWORD1".format(separator=KEYWORD_SEP)
KEYWORD_FORMAT_METHOD = u"{{method}}{separator}KEYWORD2".format(separator=KEYWORD_SEP)
KEYWORD_FORMAT_CONSTANT = u"{{constant}}{separator}LITERAL1".format(separator=KEYWORD_SEP)
class ClassKeywords:
def __init__(self, name, filename=None):
self.name = name
self.filename = filename
self._methods = []
def add_method(self, method_name):
self._methods.append(method_name)
def get_methods(self):
return sorted(set(self._methods))
def parse_library(library_path, max_depth=1):
header_files = find_header_files(library_path, max_depth)
classes = []
for header in header_files:
classes.extend(parse_header(header))
return classes
def find_header_files(library_path, max_depth=1):
header_files = []
# Max depth script borrowed from John Scmiddt (http://stackoverflow.com/a/17056922)
for d in range(1, max_depth + 1):
maxGlob = "/".join("*" * d)
topGlob = os.path.join(library_path, maxGlob)
allFiles = glob.glob(topGlob)
for file in allFiles:
if fnmatch.fnmatch(os.path.basename(file), '*.h'):
header_files.append(file)
return header_files
def parse_header(header_path):
try:
cpp_header = CppHeaderParser.CppHeader(header_path)
classes = []
for class_name, header_class in cpp_header.classes.items():
keyword_class = ClassKeywords(class_name, header_path)
for method in header_class["methods"]["public"]:
# Ignore constructors and destructors
if not (method["constructor"] or method["destructor"]):
keyword_class.add_method(method["name"])
classes.append(keyword_class)
return classes
except CppHeaderParser.CppParseError as e:
print(e)
return []
def get_keywords_fullpath(keywords_path):
if(os.path.isdir(keywords_path)):
keywords_path = os.path.join(keywords_path, KEYWORDS_FILENAME)
else:
keywords_path = keywords_path
return os.path.abspath(keywords_path)
def output_keywords(classes, keywords_file, additional_constants=None):
for output_class in classes:
keywords_file.write(KEYWORD_FORMAT_CLASS.format(class_name=output_class.name))
keywords_file.write("\n")
for method in output_class.get_methods():
keywords_file.write(KEYWORD_FORMAT_METHOD.format(method=method))
keywords_file.write("\n")
if additional_constants is not None:
for constant in additional_constants:
keywords_file.write(KEYWORD_FORMAT_CONSTANT.format(constant=constant))
keywords_file.write("\n")
|
ArduinoKeywords
|
/ArduinoKeywords-1.0.4.tar.gz/ArduinoKeywords-1.0.4/arduinokeywords/arduinokeywords.py
|
arduinokeywords.py
|
`Arduinozore`
=============
.. image:: https://travis-ci.org/S-Amiral/arduinozore.svg?branch=master
:target: https://travis-ci.org/S-Amiral/arduinozore
:alt: Build status
.. image:: https://img.shields.io/badge/License-MIT-yellow.svg
:target: http://doge.mit-license.org
:alt: MIT License
.. image:: https://img.shields.io/pypi/v/Arduinozore.svg?maxAge=2592000
:target: https://pypi.org/project/Arduinozore/
:alt: PyPI - Python Version
.. image:: https://img.shields.io/pypi/pyversions/Arduinozore.svg
:target: https://pypi.org/project/Arduinozore/
:alt: PyPI - Python Version
Realization of a web interface allowing to visualize sensors data sent by an arduino on a serial port.
This package can be installed via :code:`pip install arduinozore`.
We are still working on this README.
------------------------------------
Français
--------
L'installation est aisée. Le package se trouvant sur pypi, il suffit de l'installer via la commande
.. code-block:: bash
pip install arduinozore
Lors du premier lancement, si aucun dossier de configuration n'est trouvé, il est créé.
**Attention** Il est nécessaire d'avoir une connexion internet pour utiliser pip et lors du premier lancement de l'application. Des fichiers doivent être téléchargés depuis internet.
Pour afficher l'aide, la commande suivante est disponible
.. code-block:: bash
arduinozore --help
usage: arduinozore [-h] [-hp HTTP_PORT] [-hsp HTTPS_PORT] [-a path]
[--newconfig]
Arduinozore server
optional arguments:
-h, --help show this help message and exit
-hp HTTP_PORT, --http_port HTTP_PORT
Server http port. Default 8000
-hsp HTTPS_PORT, --https_port HTTPS_PORT
Server https port. Default 8001. Used for sockets too.
-a path, --arduino path
Path where arduino source code will be generated.
--newconfig Delete actual config and make a new one. Warning.
En cas de problème, il est possible de supprimer la configuration et la regénérer avec la commande
.. code-block:: bash
arduinozore --newconfig
Il est possible de spécifier les ports http et https. Par défaut les ports 8000 et 8001 sont utilisés. Pour ce faire, les options suivantes sont disponibles
.. code-block:: bash
arduinozore -hp 80 -hsp 443
Afin de récupérer le script arduino pour pouvoir le flasher, il est possible de l'obtenir avec l'option `-a` en donnant le path cible.
.. code-block:: bash
arduinozore -a /destination/path/for/arduino/script
Pour lancer l'application, il suffit d'exécuter
.. code-block:: bash
arduinozore
et de se rendre à l'adresse fournie dans le terminal.
**Attention**, si votre réseau domestique ne possède pas de serveur DNS, il sera nécessaire de remplacer l'adresse du serveur par son adresse IP afin de pouvoir y accéder.
Pour trouver cette adresse IP, la commande suivante suffit.
.. code-block:: bash
ifconfig
Par exemple, si lors du lancement, la chose suivante est affichée dans la console
.. code-block:: bash
/############################################################################################\
#
# # ##### ##### # # # # # #### ###### #### ##### ######
# # # # # # # # # ## # # # # # # # # #
# # # # # # # # # # # # # # # # # # # #####
####### ##### # # # # # # # # # # # # # ##### #
# # # # # # # # # # ## # # # # # # # #
# # # # ##### #### # # # #### ###### #### # # ######
\############################################################################################/
/############################################################################################\
Listening on: https://raspberry:8001
mais que vous ne possédez pas de dns, il faudra remplacer le nom "raspberry" par l'adresse IP du Raspberry Pi obtenue grâce à la commande "ifconfig".
Maintenant, il n'y a plus qu'à ouvrir un navigateur, se rendre à l'adresse correcte et effectuer quelques réglages et le tour est joué!
Tout d'abord, le navigateur risque de vous dire que le certificat n'a pas pu être vérifié. Étant donné qu'il est généré par l'application, il est autosigné. Il suffit donc de l'accepter tel quel.
Dès lors, la page d'accueil du site apparaît. Si des Arduinos sont connectés, il sont listés.
À présent, il est nécessaire de créer une configuration de carte en fonction du type d'Arduino que vous possédez. Cette création peut être atteinte dans les réglages.
Ensuite, il est nécessaire de configurer le ou les capteurs utilisés de la même manière que la ou les cartes.
Il est maintenant possible de configurer l'Arduino et d'interagir avec lui! Bravo!
|
Arduinozore
|
/Arduinozore-1.1.3.tar.gz/Arduinozore-1.1.3/README.rst
|
README.rst
|
import argparse
import os
import socket
import sys
from shutil import copyfile
from shutil import get_terminal_size
from shutil import rmtree
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
from arduinozore.handlers.error404handler import My404Handler
from arduinozore.handlers.serialManager import SerialManager
from arduinozore.handlers.ws import WSHandler
from arduinozore.settings import ARDUINO_CODE_FILE_NAME
from arduinozore.settings import ARDUINO_FILE_PATH
from arduinozore.settings import CERT_FOLDER
from arduinozore.settings import CERT_INSTALLER_PATH
from arduinozore.settings import CONFIG_FOLDER
from arduinozore.settings import PORT
from arduinozore.settings import SSL_PORT
from arduinozore.settings import STATIC_INSTALLER_PATH
from arduinozore.settings import STATIC_PATH
from arduinozore.settings import path
from arduinozore.settings import settings
from arduinozore.settings import ssl_opts
from arduinozore.urls import url_pattern
from pyfiglet import Figlet
STATIC_CMD = "chmod +x " + STATIC_INSTALLER_PATH + " && " + STATIC_INSTALLER_PATH
CERT_CMD = "chmod +x " + CERT_INSTALLER_PATH + " && " + CERT_INSTALLER_PATH
def main():
"""Catch main function."""
p = argparse.ArgumentParser(
description="Arduinozore server", prog="arduinozore")
p.add_argument('-hp',
'--http_port',
type=int,
help='Server http port. Default ' + str(PORT))
p.add_argument('-hsp',
'--https_port',
type=int,
help='Server https port. Default ' + str(SSL_PORT) + '. Used for sockets too.')
p.add_argument('-a',
'--arduino',
type=str,
metavar='path',
help='Path where arduino source code will be generated.')
p.add_argument('--newconfig',
action="store_true",
help='Delete actual config and make a new one. Warning.')
args = p.parse_args()
if args.arduino:
copy_arduino_code(args.arduino)
if args.newconfig:
if os.path.exists(CONFIG_FOLDER):
rmtree(CONFIG_FOLDER)
http_port = PORT if args.http_port is None else args.http_port
ssl_port = SSL_PORT if args.https_port is None else args.https_port
check_config_folder()
serial_manager = SerialManager()
try:
if not serial_manager.is_alive():
serial_manager.start()
index_application = tornado.web.Application(
url_pattern, default_handler_class=My404Handler, **settings)
index_application.listen(http_port)
http_server = tornado.httpserver.HTTPServer(
index_application,
ssl_options=ssl_opts
)
http_server.listen(ssl_port)
tornado.ioloop.PeriodicCallback(WSHandler.write_to_clients, 500).start()
terminal_width = get_terminal_size((80, 20))[0]
introduction(ssl_port, terminal_width)
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
print('Exiting...'.center(terminal_width))
except Exception as e:
print(e)
sys.exit()
finally:
serial_manager.join()
def introduction(ssl_port, terminal_width):
"""Show a message to the user so he knows who we are."""
app_name = ' Arduinozore'
TOPBAR = '#' * (terminal_width - 2)
print('/' + TOPBAR + '\\' + "\n")
print(Figlet(font='banner').renderText(app_name))
print('\\' + TOPBAR + '/' + "\n")
print('/' + TOPBAR + '\\' + "\n")
HOST = socket.gethostname()
PORT = ssl_port
message = 'Listening on: https://{}:{}'.format(HOST, PORT)
print(message.center(terminal_width))
sys.stdout.flush()
def check_config_folder():
"""Check if config folder exists, otherwise creates it."""
try:
if not os.path.exists(CONFIG_FOLDER):
print("No configuration folder found, creating one")
os.makedirs(CONFIG_FOLDER)
os.makedirs(CERT_FOLDER)
os.makedirs(STATIC_PATH)
os.system(STATIC_CMD)
os.system(CERT_CMD)
print("Configuration folder created with success.")
except Exception as e:
exit(e)
def copy_arduino_code(dest):
"""Copy arduino source code to dest."""
dst = path(dest, ARDUINO_CODE_FILE_NAME)
copyfile(ARDUINO_FILE_PATH, dst)
print("File copied to " + dst)
exit(0)
if __name__ == "__main__":
main()
|
Arduinozore
|
/Arduinozore-1.1.3.tar.gz/Arduinozore-1.1.3/arduinozore/__main__.py
|
__main__.py
|
import tornado
from arduinozore.handlers.baseHandler import BaseHandler
from tornado.escape import url_unescape
class CrudHandler(BaseHandler):
"""Arduino page handler."""
@tornado.web.asynchronous
def get(self, slug=None, method=None):
"""Handle get request."""
if slug is None:
self.list()
return
slug = url_unescape(slug)
if slug == 'create':
self.create()
else:
if method is None:
self.show(slug)
elif method == 'edit':
self.edit(slug)
elif method == 'create':
self.create(slug)
else:
self.render("404.html")
@tornado.web.asynchronous
def post(self, slug=None, method=None):
"""
Handle get request.
Broswers can't send put and delete request so we have to fake them.
"""
try:
_method = self.get_argument('_method')
except Exception:
_method = None
if slug is None and _method is None:
self.store()
return
elif _method is None:
self.store(slug)
return
try:
slug = url_unescape(slug)
except AttributeError:
pass
if _method == 'put':
self.put(slug, method)
return
elif _method == 'delete':
self.delete(slug, method)
return
else:
self.render("404.html")
def put(self, slug, method=None):
"""Handle put request."""
self.update(slug)
def delete(self, slug, method=None):
"""Handle delete request."""
self.destroy(slug)
def list(self):
"""Show device."""
pass
def show(self, slug):
"""Show device."""
pass
def create(self, slug=None):
"""Show configuration form for device."""
pass
def edit(self, slug):
"""Show configuration form for device."""
pass
def store(self, slug):
"""Store configuration."""
pass
def update(self, slug):
"""Update configuration."""
pass
def destroy(self, slug):
"""Destroy configuration."""
pass
|
Arduinozore
|
/Arduinozore-1.1.3.tar.gz/Arduinozore-1.1.3/arduinozore/handlers/crudHandler.py
|
crudHandler.py
|
import json
import sys
import time
from multiprocessing import Event
from multiprocessing import Manager
from multiprocessing import Process
from arduinozore.handlers.serialReader import SerialReader
class Singleton(type):
"""
Singleton metaclass.
From https://stackoverflow.com/q/6760685/9395299.
"""
_instances = {}
def __call__(cls, *args, **kwargs):
"""Instantiate singleton or return."""
if cls not in cls._instances:
cls._instances[cls] = super(
Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class SerialManager(Process, metaclass=Singleton):
"""Process class."""
def __init__(self):
"""Init process."""
Process.__init__(self)
self.exit = Event()
self.serial_readers = {}
self.datas = Manager().dict()
self.out = Manager().dict()
def toggle_pin(self, port, pin):
"""Toggle pin on card connected to port."""
if port not in dict(self.out):
self.out[port] = pin
sys.stdout.flush()
def get_toggelable_pin(self, port):
"""Return toggelable pins for port."""
try:
toggle = self.out[port]
del self.out[port]
return toggle
except KeyError:
return None
def finish(self, port):
"""Finish serial reader process."""
if port in self.serial_readers:
self.serial_readers[port].shutdown()
del self.serial_readers[port]
def set_datas(self, port, datas):
"""Set data from child process."""
self.datas[port] = json.dumps(datas)
def get_serial_reader(self, port):
"""Get datas for specified serial port."""
if port not in self.serial_readers:
self.serial_readers[port] = SerialReader(port, self)
self.serial_readers[port].start()
def get_datas_for_port(self, port):
"""Get datas for serial port."""
self.get_serial_reader(port)
try:
return self.datas[port]
except (KeyError, Exception):
self.datas[port] = 'Initializing reader'
return self.datas[port]
def run(self):
"""Run process."""
while not self.exit.is_set():
try:
# print("Manager running")
# sys.stdout.flush()
time.sleep(1)
except (KeyboardInterrupt, RuntimeError) as e:
self.shutdown()
except Exception as e:
raise e
finally:
for s_r in self.serial_readers:
self.serial_readers[s_r].join()
def shutdown(self):
"""Shut down process."""
self.exit.set()
|
Arduinozore
|
/Arduinozore-1.1.3.tar.gz/Arduinozore-1.1.3/arduinozore/handlers/serialManager.py
|
serialManager.py
|
from arduinozore.handlers.crudHandler import CrudHandler
from arduinozore.models.sensor import Sensor
from tornado.escape import url_escape
class SensorHandler(CrudHandler):
"""Sensor handler."""
def list(self):
"""List configurations."""
sensors = Sensor.get_all()
self.render('sensor/list.html', sensors=sensors)
def show(self, slug):
"""Show device."""
sensor = Sensor.get(slug)
if sensor is not None:
self.render('sensor/show.html', sensor=sensor, slug=slug)
else:
self.redirect('/sensor', permanent=False)
def create(self):
"""Show configuration form for device."""
settings = dict()
settings['sensor'] = None
settings['method'] = 'post'
self.render('sensor/config.html', **settings)
def edit(self, slug):
"""Show configuration form for device."""
sensor = Sensor.get(slug)
settings = dict()
settings['sensor'] = sensor
settings['method'] = 'put'
self.render('sensor/config.html', **settings)
def store(self, slug=""):
"""Create configuration."""
sensor_name = self.get_argument('name')
self.save(sensor_name)
def update(self, slug):
"""Update configuration."""
self.save(slug)
def save(self, slug):
"""Save configuration."""
sensor_name = slug
min_value = self.get_argument('min_value')
max_value = self.get_argument('max_value')
suffix = self.get_argument('suffix')
reverse = True if 'reverse' in self.request.arguments else False
sensor = Sensor(sensor_name, min_value, max_value, reverse, suffix)
sensor.save()
slug = url_escape(slug)
redirect_url = self.redirect_url
if slug not in redirect_url:
redirect_url += '/' + slug
self.redirect(redirect_url, permanent=True)
def destroy(self, slug):
"""Destroy configuration."""
sensor = Sensor.get(slug)
sensor.delete()
self.redirect(self.redirect_url, permanent=False)
|
Arduinozore
|
/Arduinozore-1.1.3.tar.gz/Arduinozore-1.1.3/arduinozore/handlers/sensor.py
|
sensor.py
|
import re
import sys
import time
from multiprocessing import Event
from multiprocessing import Manager
from multiprocessing import Process
from arduinozore.models.device import Device
from arduinozore.models.sensor import Sensor
from serial import Serial
class SerialReader(Process):
"""Process class."""
def __init__(self, serial_port, parent):
"""Init process."""
Process.__init__(self)
self.exit = Event()
self.serial_port = serial_port
self.device = Device.get(Device.get_identifier_from_serial(serial_port))
self.get_port_list()
self.ser = None
self.parent = parent
self.parent.set_datas(self.serial_port, dict(self.value))
def get_port_list(self):
"""Get port list from config."""
self.ports = Manager().dict()
self.value = Manager().dict()
self.sensors = dict()
for p in self.device.ports['input']:
if p.enabled:
self.ports[p.number] = p
self.value[p.number] = 'Connexion à la carte'
self.sensors[p.number] = Sensor.get(p._type)
def get_datas(self):
"""Return datas."""
return self.value
def run(self):
"""Run process."""
self.init_serial()
while not self.exit.is_set():
try:
self.read_serial()
except (KeyboardInterrupt, RuntimeError) as e:
self.shutdown()
except Exception as e:
exit(e)
finally:
try:
self.ser.close()
except AttributeError:
pass
# print("You exited!")
def shutdown(self):
"""Shut down process."""
self.exit.set()
def init_serial(self):
"""Init serial port."""
# Can't put it in init otherwise makes an error...
self.ser = Serial(self.serial_port, timeout=None, baudrate=38400)
self.pattern = re.compile(r'[\t\r\n]+')
msg2 = 'You can now ask for reading [r] or writing [w].'
self.ser.read(self.ser.inWaiting())
datas = re.sub(self.pattern, '', self.ser.readline().decode())
while datas != msg2:
self.ser.write("ok".encode())
time.sleep(0.4)
datas = re.sub(self.pattern, '', self.ser.readline().decode())
# print(datas)
sys.stdout.flush()
def read_serial(self):
"""Read serial port."""
try:
while not self.exit.is_set():
self.ser.read(self.ser.inWaiting())
self.get_port_list()
for port in dict(self.ports):
self.ser.read(self.ser.inWaiting()).decode()
self.ser.write('r'.encode() + str.encode(str(port)))
data = re.sub(self.pattern, '',
self.ser.readline().decode())
if self.sensors[port] is not None:
self.value[port] = self.sensors[port].transform_datas(
data)
else:
self.value[port] = data
self.parent.set_datas(self.serial_port, dict(self.value))
port = self.parent.get_toggelable_pin(self.serial_port)
if port is not None:
self.ser.read(self.ser.inWaiting()).decode()
self.ser.write('w'.encode() + str.encode(str(port)))
except (KeyboardInterrupt) as e:
exit()
|
Arduinozore
|
/Arduinozore-1.1.3.tar.gz/Arduinozore-1.1.3/arduinozore/handlers/serialReader.py
|
serialReader.py
|
import os
from arduinozore.handlers.crudHandler import CrudHandler
from arduinozore.handlers.tools import get_arduino
from arduinozore.handlers.tools import get_config_name
from arduinozore.models.card import Card
from arduinozore.models.device import Device
from arduinozore.models.sensor import Sensor
from arduinozore.settings import DEVICE_CONFIG_FOLDER
from arduinozore.settings import SSL_PORT
from arduinozore.settings import path
class DevicePageHandler(CrudHandler):
"""Device page handler."""
default_args = {'enabled': '', 'name': '', 'type': ''}
def list(self):
"""List configuration."""
devices = Device.get_all()
self.render('device/list.html', devices=devices)
def show(self, slug):
"""Show device."""
device = Device.get(Device.get_identifier_from_serial(slug))
if device is None:
device = Device.get_config(slug)
if device is None:
self.redirect(self.redirect_url + '/create', permanent=False)
else:
settings = dict()
settings['device'] = device
settings['slug'] = slug
self.render('device/show.html', **settings)
else:
settings = dict()
settings['port'] = SSL_PORT
settings['slug'] = slug
settings['device'] = device
self.render('device/communicate.html', **settings)
def create(self, slug):
"""Show configuration form for device."""
cards = Card.get_all()
sensors = Sensor.get_all()
device = Device.get(slug)
if 'card' in self.request.arguments:
card = Card.get(self.get_argument('card'))
else:
card = None
settings = dict()
settings['method'] = 'post'
settings['cards'] = cards
settings['card'] = card
settings['sensors'] = sensors
settings['device'] = device
settings['slug'] = slug
settings['method'] = 'post'
self.render('device/config.html', **settings)
def edit(self, slug):
"""Show configuration form for device."""
device = Device.get(Device.get_identifier_from_serial(slug))
cards = Card.get_all()
sensors = Sensor.get_all()
if device is None:
device = Device.get_config(slug)
if device is None:
self.redirect(self.redirect_url + '/create', permanent=False)
settings = dict()
settings['method'] = 'put'
settings['cards'] = cards
settings['card'] = device.card
settings['sensors'] = sensors
settings['device'] = device
settings['method'] = 'put'
self.render('device/config.html', **settings)
def store(self, slug):
"""Store configuration."""
self.save(slug)
self.redirect(self.redirect_url, permanent=True)
def update(self, slug):
"""Update configuration."""
self.save(slug)
self.redirect(self.redirect_url, permanent=True)
def save(self, slug):
"""Save configuration."""
try:
self.request.arguments.pop("_method")
except Exception:
pass
device = Device.from_request_args(slug, self.request.arguments)
device.save()
def destroy(self, slug):
"""Destroy configuration."""
arduino = get_arduino(slug)
config_name = get_config_name(arduino)
config_file = path(DEVICE_CONFIG_FOLDER, config_name)
os.remove(config_file)
self.redirect(self.redirect_url, permanent=False)
|
Arduinozore
|
/Arduinozore-1.1.3.tar.gz/Arduinozore-1.1.3/arduinozore/handlers/device.py
|
device.py
|
import base64
import os
from arduinozore.settings import path
from yaml import SafeLoader
from yaml import YAMLObject
from yaml import dump
from yaml import safe_load
class Model(YAMLObject):
"""Model default class."""
yaml_tag = u'!Model'
yaml_loader = SafeLoader
def __init__(self, name):
"""Init model."""
self.name = name
def __repr__(self):
"""Represent model in order to save it."""
return "%s(name=%r)" % (self.__class__.__name__, self.name)
@classmethod
def load_yaml(cls, folder, filename):
"""Load yaml from file."""
try:
with open(path(folder, filename), 'r') as f:
model = safe_load(f)
except (FileExistsError, FileNotFoundError):
model = None
return model
def save_yaml(self, folder):
"""Save model to file."""
config_file = self.get_filename()
config_file = path(folder, config_file)
with open(config_file, 'w') as f:
d = dump(self, default_flow_style=False,
allow_unicode=True, encoding=None)
f.write(d)
def get_filename(self):
"""Get filename to save."""
return __class__.filenamify(self.name) + ".yaml"
def _delete(self, folder):
"""Delete model file."""
os.remove(path(folder, self.get_filename()))
@classmethod
def filenamify(cls, name):
"""Return filename base64 encoded from filename."""
return base64.urlsafe_b64encode(name.encode('UTF-8')).decode()
@classmethod
def unfilenamify(cls, filename):
"""Return filename base64 decoded from filename."""
return base64.urlsafe_b64decode(filename.encode()).decode('UTF-8')
@classmethod
def _get_all(cls, folder):
"""Get all models configurations."""
models = list()
if not os.path.exists(folder):
os.makedirs(folder)
config_files = os.listdir(folder)
if config_files is not None and len(config_files) > 0:
for config_file in config_files:
model = cls.load_yaml(folder, config_file)
models.append(model)
else:
models = None
return models
@classmethod
def _get(cls, name, folder):
"""Get model by name."""
try:
model = cls.load_yaml(folder, cls.filenamify(name) + ".yaml")
except Exception:
model = None
return model
|
Arduinozore
|
/Arduinozore-1.1.3.tar.gz/Arduinozore-1.1.3/arduinozore/models/model.py
|
model.py
|
from arduinozore.models.card import Card
from arduinozore.models.model import Model
from arduinozore.settings import DEVICE_CONFIG_FOLDER
from serial.tools import list_ports
class Port(Model):
"""Port class."""
yaml_tag = u'!Port'
def __init__(self, name, number, enabled, _type="output"):
"""Init port."""
self.name = name
self._type = _type
self.number = number
self.enabled = enabled if enabled is True or False else (
True if enabled == 'on' else False)
def __repr__(self):
"""Represent port in order to save it."""
return "%s(number=%r, name=%r, _type=%r, enabled=%r)" % (
self.__class__.__name__, self.number, self.name, self._type, self.enabled)
class Device(Model):
"""Device class."""
yaml_tag = u'!Device'
def __init__(self, name, identifier, card_name):
"""Init device."""
self.name = name
self.identifier = identifier
self.card = Card.get(card_name)
self.init_ports()
def save(self):
"""Save device."""
self.save_yaml(DEVICE_CONFIG_FOLDER)
def delete(self):
"""Delete device."""
self._delete(DEVICE_CONFIG_FOLDER)
def __repr__(self):
"""Represent device in order to save it."""
return "%s(name=%r, identifier=%r, card=%r, ports=%r)" % (
self.__class__.__name__, self.name, self.identifier, self.card, self.ports)
def init_ports(self):
"""Init port list."""
self.ports = {'input': list(), 'output': list()}
for i in range(self.card.nb_input_pins):
self.ports['input'].append(Port(
number=i, name="", enabled="False", _type=""))
for i in range(self.card.nb_output_pins):
self.ports['output'].append(Port(
number=i, name="", enabled="False", _type=""))
def add_port_from_dict(self, port, dict):
"""Create port and add from dict."""
port = int(port.replace("port", ""))
if port >= self.card.nb_input_pins:
port = port - self.card.nb_input_pins
p = Port(number=port, **dict)
_type = p._type if p._type == "output" else "input"
port_to_replace = next(
(self.ports[_type].index(port) for port in self.ports[_type] if p.number == port.number), None)
self.ports[_type][port_to_replace] = p
def get_filename(self):
"""Get filename to save."""
return __class__.filenamify(self.identifier) + ".yaml"
@classmethod
def get_arduinos(cls):
"""Get list of connected arduinos."""
serials = list(list_ports.comports())
arduinos = [s for s in serials if 'Arduino' in s.description or (
s.manufacturer is not None and 'Arduino' in s.manufacturer)]
return arduinos
@classmethod
def get_all(cls):
"""Get all device configurations."""
return __class__._get_all(DEVICE_CONFIG_FOLDER)
@classmethod
def get(cls, name):
"""Get device by name."""
return __class__._get(name, DEVICE_CONFIG_FOLDER)
@classmethod
def get_connected_devices(cls):
"""Get devices connected."""
arduinos = cls.get_arduinos()
devices = {a.device: __class__.get(__class__.get_identifier(
a)) for a in arduinos}
return devices
@classmethod
def get_config(cls, name):
"""Get config by name."""
configs = cls.get_all()
if configs is not None:
return next(
(config for config in configs if config.name == name), None)
else:
return configs
@classmethod
def get_identifier_from_serial(cls, serial):
"""Get device identifier from serial name."""
arduinos = cls.get_arduinos()
arduino = next(
(arduino for arduino in arduinos if serial in arduino.device), None)
return __class__.get_identifier(arduino)
@classmethod
def get_identifier(cls, arduino):
"""Get identifier from arduino."""
if arduino is not None:
config_name = str(arduino.vid)
config_name += str(arduino.pid)
config_name += str(arduino.serial_number)
return config_name
else:
return None
@classmethod
def from_request_args(cls, slug, args):
"""Init device from request args."""
args = {arg: args[arg][0].decode() for arg in args}
res = dict()
for arg in args:
if '[' in arg and ']' in arg:
split_arg = arg.split('[')
var_name = split_arg[0]
index = split_arg[1].split(']')[0]
if var_name not in res:
res[var_name] = dict()
res[var_name][index] = args[arg]
else:
res[arg] = args[arg]
if 'identifier' not in res:
identifier = cls.get_identifier_from_serial(slug)
else:
identifier = res.pop('identifier')
dev = cls(res.pop('name'), identifier,
res.pop('card_name'))
for port in res:
dev.add_port_from_dict(port, res[port])
return dev
|
Arduinozore
|
/Arduinozore-1.1.3.tar.gz/Arduinozore-1.1.3/arduinozore/models/device.py
|
device.py
|
Les différentes étapes sont tirées directement des messages de commit Git.
Elles sont présentées de la plus récente à la plus ancienne.
2018-05-03 19:29:11
-------------------
Updated doc
2018-04-30 09:08:51
-------------------
Added doc + little fix
- Moved arduino code to another folder
- Completed french part of readme
2018-04-27 11:01:52
-------------------
Fixes for raspbery plateform.
- Updated Arduinos recognition from serial ports.
- Deleted a few useless "print".
2018-04-16 08:52:03
-------------------
Added semantic installer in setup
2018-04-16 08:39:24
-------------------
Updated README
2018-04-15 18:06:00
-------------------
Added python3.4 & 3.5 support
- Corrected errors
- Added test for travis
- Plus a few fixes
2018-04-13 11:35:48
-------------------
Enabled Travis and made a bit of cleaning
2018-03-23 13:24:46
-------------------
Added command line parser
- Added an introduction message
- Added creation of config folder
- Made a bit of cleaning too
- Added setup
2018-03-16 13:13:58
-------------------
Added digital port toggling.
- You can now toggle a port by clicking on the corresponding button.
2018-03-12 10:27:03
-------------------
Added sensors and cards
- Added model, view(template), controller(Handler) for sensors and cards.
2018-03-09 06:07:24
-------------------
Major update
- Added index page that lists connected devices
- Added table for viewing sensors values in device page
- Added a serial manager to manager sensor readers (avoids multiple opening of serial ports which raises an error)
- Added subprocesses for reading serial ports
2018-03-06 08:13:40
-------------------
[structure] Refonte majeur
- La partie web du projet est maintenant plus hierarchisée donc moins brouillon.
- Structure:
- - Un dossier pour les handlers
- - Un dossier static pour les assets (semantic installable via le script semantic_installer.sh)
- - Un dossier pours les templates
- - Un fichier main qui lance le serveur
- - Un fichier qui contient les capteurs (à voir comment on fait dans le futur)
- - Un fichier de config
- - Un fichier d'urls
2018-02-23 14:03:02
-------------------
Project base
- Still a lot of shit to clean.. Sorry for this..
2018-02-23 13:52:04
-------------------
Initial commit
|
Arduinozore
|
/Arduinozore-1.1.3.tar.gz/Arduinozore-1.1.3/doc/journalDeTravail/journalDeTravail.rst
|
journalDeTravail.rst
|
.. role:: raw-latex(raw)
:format: latex
Lexique
=======
Afin de simplifier la lecture, un lexique est présenté ci-après.
.. table:: Lexique
:widths: auto, 60
=================== ============
Mot clé Définition
------------------- ------------
Python Le langage de programmation utilisé pour le développement de l'application. Un programme python nécessite d’être exécuté par un interpréteur Python. Un programme Python dépend souvent d’un certain nombre de packages Python.
Package Un ensemble de fonctionnalités implémentées et offertes par des membres de la communauté Python, afin d’étendre les possibilités du langage. Un package utilisé par un programme Python doit être installé sur l’ordinateur du client. Arduinozore utilisant de multiples packages, il est nécessaire de les installer avant de pouvoir utiliser l'application.
Arduino Un Arduino est une petite carte électronique facilitant l'apprentissage de l'électronique et la programmation ainsi que le prototypage :raw-latex:`\cite{arduino_home_page}`.
RaspberryPi Un RaspberryPi est un mini-ordinateur équipé d'un microprocesseur ARM et 256 à 512 mo de RAM. L'intérêt du produit se trouve dans sa très faible consommation en énergie et son coût très bas. :raw-latex:`\cite{raspberry_home_page}`.
WebSocket Le protocole WebSocket vise à développer un canal de communication full-duplex sur un socket TCP pour les navigateurs et les serveurs web :raw-latex:`\cite{wiki_websocket}`. En une phrase simple : les WebSockets permettent de créer des applications temps-réel sur le web :raw-latex:`\cite{binio}`.
YAML YAML Ain't Markup Language. YAML est un format de représentation de données par sérialisation Unicode. L'idée de YAML est que presque toute donnée peut être représentée par combinaison de listes, tableaux associatifs et données scalaires. YAML décrit ces formes de données (les représentations YAML), ainsi qu'une syntaxe pour présenter ces données sous la forme d'un flux de caractères (le flux YAML) :raw-latex:`\cite{wiki_YAML}`. Ce langage de stockage de données permet d'éviter l'utilisation d'une base de donnée qui serait lourde pour ce projet. Il stocke les données sérialisée directement dans un fichier sur le disque. De plus, il permet de charger les fichiers de manière sécurisée afin d'éviter les injections de code.
=================== ============
:raw-latex:`\medskip`
Introduction
============
La domotique prenant de plus en plus de place dans les foyers modernes et les prix de ces systèmes étant élevés, il a été nécessaire d'essayer de trouver une alternative moins coûteuse.
:raw-latex:`\medskip`
Les cartes Arduinos ainsi que RaspberryPi restant relativement bon marché malgré leurs capacités toujours plus grandes, le choix s'est porté sur ces modèles. Ces deux équipements n'étant pas prévu pour communiquer ensemble de manière native, il est nécessaire de développer une solution leur permettant de se comprendre. Cependant, le projet étant destiné à un usage open source, il est préférable de garder un système dans lequel l'Arduino peut communiquer avec un autre matériel que le PI.
:raw-latex:`\medskip`
La figure $\ref{img/diagrammeCommunication.png}$ représente la communication entre les différents composants de notre système
.. figure:: img/diagrammeCommunication.png
:width: 90%
:height: 80%
:alt: diagramme de communication
Diagramme de communication entre les composants
Le but de ce projet est de pouvoir visualiser via une interface web les valeurs de capteurs connectés à un RaspberryPi.
:raw-latex:`\newpage`
Rappel des objectifs
====================
Récupération des données
^^^^^^^^^^^^^^^^^^^^^^^^
1. Trouver un moyen de pouvoir lire n'importe quel capteur depuis l'arduino et envoyer la valeur sur le port série. Ne pas faire de traitement, juste lire les valeurs et les transmettre. Produire un code "générique".
2. Développer un logiciel(python ou autre) qui lise ce paramètre sur le port série et qui l'interprète en fonction de configurations mises en place auparavant.
3. Développer une appli web ou desktop qui permette de se connecter au pi et d'afficher les données de manière lisible.
Activation de relais
^^^^^^^^^^^^^^^^^^^^
1. Produire un code générique pour pouvoir activer ou désactiver une gpio de manière générique.
2. Ajouter au logiciel la possibilité de trigger ce relai.
3. Ajouter à l'appli web la même possibilité.
Global
^^^^^^
1. Trouver un moyen de donner un nom à l'arduino pour l'identifier sur le port com. "Salon" donne plus d'infos que "Arduino Uno sur COM1"
Secondaires
^^^^^^^^^^^
1. Modifier l'appli web pour ajouter la possibilité de paramétrer les nouveaux capteurs ou relais depuis là de manière simple. (Des clics sur des boutons sont toujours plus agréables que la ligne de commande pour les utilisateurs lambda)
2. Ajouter la possibilité de rajouter des capteurs sur les arduinos. Ils disposent de 6 entrées analogiques, autant toutes les utiliser.
Fonctionnalités implémentées
============================
En l'état, une fois lancé, le programme est capable de récupérer les données des capteurs branchés à un Arduino ainsi que de changer l'état de ses sorties afin, par exemple, de faire commuter un relais.
Arduino
^^^^^^^
Pour que l'Arduino soit capable de communiquer via le port série, il est nécessaire de déterminer un protocole de communication.
:raw-latex:`\medskip`
La figure $\ref{img/diagrammeEtatArduino.png}$ illustre ce protocole.
:raw-latex:`\medskip`
.. figure:: img/diagrammeEtatArduino.png
:alt: diagramme d'état arduino
Diagramme du protocole de communication
Tout d'abord, lorsque l'Arduino est allumé, il s'annonce en continu tant que l'appareil en face ne lui envoie pas la commande `ok`. Suite à cela, il est possible de consulter la valeur d'une entrée ou de changer l'état d'une sortie.
Pour ce faire, les commandes sont les suivantes:
.. code-block:: bash
usage:
- lire les données disponibles sur le port série
- envoyer "ok" pour commencer
- lire les données disponibles sur le port série
- envover:
- "w" + [NUMERO_SORTIE] pour changer l état d une sortie
- "r" + [NUMERO_ENTREE] pour lire la valeur d une entrée
Lors du changement d'état d'une sortie, l'Arduino ne renvoie rien.
Par contre, lors de la lecture d'une entrée, l'Arduino renvoie la valeur lue sans traitement. La valeur est comprise entre 0 (0 volt) et 1023 (5 volts). La précision est donc de 0.005 volts.
Communication avec les Arduinos
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Afin de communiquer avec les arduinos, le package Python PySerial est utilisé. Il permet de faciliter l'usage d'un port série en python. Dès lors, il est simple de respecter le protocole de communication décrit ci-dessus.
Interface web
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Afin d'afficher les mesures et de pouvoir changer l'état des sorties, une interface web est présent. Il permet depuis la page d'accueil d'afficher les Arduinos connectés et de les configurer. Il permet la création de capteurs afin d'enregistrer les configurations. Il en est de même pour les différents types de cartes Arduino.
Architecture
============
Ce chapitre décrit l'architecture du projet. En premier lieu, une brève explication sur les fichiers est donnée puis l'organisation du projet est représentée.
Arborescence du projet
^^^^^^^^^^^^^^^^^^^^^^
Comme l'illustre la figure $\ref{img/folderTree.png}$, le dossier de projet `arduinozore` est sous la forme d'un projet github :raw-latex:`\cite{github}`.
:raw-latex:`\medskip`
Il est possible d'y trouver un fichier `.gitignore`, un script de test concernant l'assurance qualité du code et son fichier de configuration, un fichier `README` expliquant brièvement le projet, les configurations pour rendre le paquet installable, les dossiers `doc` et `arduino` et le package `arduinozore`. Ce sont ces derniers qui sont expliqués.
.. figure:: img/folderTree.png
:width: 90%
:height: 120%
:alt: Arborescence du projet
Arborescence du projet
:raw-latex:`\medskip`
Le premier dossier, appelé `arduinozore`, contient lui les codes sources permettant de faire fonctionner le projet.
Le fichier `__main__.py` est le point d'entrée du projet. C'est ce package qui lance le serveur et instancie les différents process qui seront utilisés pour récupérer les données.
Le fichier `__init__.py` est un fichier utilisé pour que python traite le dossier comme un package afin de repérer les sous packages.
Le fichier `install_cert.sh` sert à générer les certificats ssl pour communiquer via https.
Le fichier `static_installer.sh` sert à télécharger les fichier statiques utilisés pour le rendu graphique de l'application.
Le fichier `settings.py` contient les réglages pour le serveur web.
Le fichier `urls.py` contient la liste des urls atteignables et leurs action respectives.
Le dossier `arduino` contient le code arduino à flasher sur les devices.
Le dossier `handlers` contient les gestionnaires qui executent les actions relatives aux urls.
Le dossier `models` contient les modèles de données servant à la lecture, manipulation et stockage des données.
Le dossier `static` contient les fichiers statiques qui seront servis par le serveur (feuilles de style en cascade, fichiers javascript, etc.).
Le dossier `templates` contient les templates de pages web utilisées pour le rendu.
Comme on peut le constater, ce package est sous la forme d'un package web.
:raw-latex:`\medskip`
Le dernier dossier, `Doc`, contient le rapport et le manuel utilisateur. Ces 2 fichiers étant réalisés en RestTructuredText, ils sont ensuite convertis en pdf en utilisant le projet Technical Report:raw-latex:`\cite{technicalreport}`. Ceci libère d'une tâche de mise en page étant donné qu'elle est générée automatiquement.
Diagramme UML
^^^^^^^^^^^^^
La figure $\ref{img/classes_Arduinozore.png}$ représente le diagramme UML du projet. Il est expliqué ci-après.
:raw-latex:`\begin{landscape}`
.. figure:: img/classes_Arduinozore.png
:width: 140%
:height: 100%
:alt: Diagramme UML
Diagramme uml
:raw-latex:`\end{landscape}`
Description des classes
^^^^^^^^^^^^^^^^^^^^^^^
La majorité des classes du package `handlers` dérivent de "BaseHandler". Cette base contient des configurations qui sont identiques à tous les autres gestionnaires.
Les classes `SerialManager` et `SerialReader` dérivent de "multiprocessing.Process" afin de pouvoir travailler simultanément. De plus amples explications peuvent être trouvées dans la section suivante.
La classe `WSHandler` dérive elle de "tornado.websocket.WebSocketHandler". Il s'agit du gestionnaire pour toutes les connexions WebSocket.
Les classes du package models dérivent quant à elles de la classe de base `Model`.
`BaseHandler`
####################
Cette classe est la classe de base de laquelle héritent tous les gestionnaires.
Elle fixe les entêtes de communication et redirige http vers https. De plus, elle localise le dossier contenant les templates.
`CrudHandler`
####################
Cette classe est la classe de base de laquelle héritent tous les gestionnaires qui permettent le CRUD :raw-latex:`\cite{wiki_crud}`. Elle hérite de la classe BaseHandler.
Cette classe permet de tromper l'utilisateur sur les méthodes HTTP utilisées. Comme les navigateurs ne peuvent pas, à l'heure actuelle, utiliser les méthodes PUT, PATCH, DELETE, cette classe permet de faire comme si ces méthodes étaient utilisées au travers de requêtes POST.
`CardHandler`
####################
Cette classe est le gestionnaire de tout ce qui touche aux cartes. Elle est capable de lire les configurations de cartes déjà enregistrées, de sauvegarder les modifications s'il y en a et d'éventuellement supprimer ces configurations. En fonction des liens atteint, elle affiche la configuration, son formulaire de création, son formulaire de modification ou la liste des configurations à disposition.
`DevicePageHandler`
####################
Cette classe est idem à la précédente si ce n'est qu'elle agit pour tout ce qui touche aux devices.
`SensorHandler`
####################
Cette classe est idem à la précédente si ce n'est qu'elle agit pour tout ce qui touche aux capteurs.
`IndexPageHandler`
####################
Cette classe est le gestionnaire de la page d'accueil. Elle est capable de récupérer les Devices connectés et de les afficher.
`SettingPageHandler`
####################
Cette classe est le gestionnaire de la page des configurations. Elle permet d'afficher les types de configuration disponibles.
`SerialManager`
####################
Cette classe est un singleton responsable d'attribuer un SerialReader pour chaque Arduino connecté. De ce fait, il est sûr que les nouveaux processus sont lancés et arrêtés proprement et qu'un seul processus est lancé par Device.
`SerialReader`
####################
Cette classe est responsable de la communication avec les devices. Afin de rendre les échanges asynchrones et de ne pas bloquer le serveur pour lire une valeur, ces classes sont des processus lancés à côté du processus parent. Ils sont gérés par la classe SerialManager.
Les processus ont été préférés aux threads car leur manipulation est plus simple en python.
`WSHandler`
####################
Cette classe est le gestionnaire des connections aux websockets. Lors de l'ouverture d'une connection (Donc lorsque l'utilisateur souhaite manipuler un arduino), elle s'assure qu'un processus de communication est lancée et fait le pont entre l'utilisateur et le SerialManager qui communique avec les SerialReaders.
`Model`
####################
Cette classe est la classe de base de laquelle héritent tous les modèles. Elle fixe les fonctions de base disponibles dans tous les modèles et configure le chargement et l'écriture des configurations sur le disque.
`Card`
####################
Cette classe est le modèle de données pour les cartes. Elle hérite de la classe Model et permet de lire et écrire les configurations sur le disque.
`Device`
####################
Cette classe est idem à la précédente si ce n'est qu'il s'agit du modèle pour les devices.
`Sensor`
####################
Cette classe est idem à la précédente si ce n'est qu'il s'agit du modèle pour les capteurs.
Multiprocessing
^^^^^^^^^^^^^^^
Le package Multiprocessing permet d'exécuter des tâches de manière concurrente. Les classes SerialManager et SerialReader sont lancées comme un ou plusieurs process et permettent donc d'exécuter des tâches en parallèle. De ce fait, les process ne peuvent pas communiquer de manière normale entre eux avec des listes, ils doivent utiliser des queues ou des variables spéciales qui empêchent les conflits d'écriture ou de lecture.
Format de données
^^^^^^^^^^^^^^^^^^^
Afin de simplifier le stockage des configurations, le format de données YAML a été choisi. Il est plus léger d'utilisation qu'une base de données pour un projet de petite envergure comme le notre.
Méthodologie
============
Le projet s'est principalement déroulé selon une méthodologie de recherches puis d'implémentation. Il a fallu se renseigner sur beaucoup d'aspect tel que la meilleure technologie à utiliser, les limitations et possibilités des Arduinos, comment communiquer entre le RaspberryPi et le(s) Arduino(s), etc.
:raw-latex:`\medskip`
Plus de la moitié du temps consacré au projet s'est déroulé dans le cadre de recherches.
De ce fait, aucun planning n'a été défini à l'avance car il était impossible d'évaluer le temps nécessaire pour effectuer ces recherches. Le projet s'est donc déroulé de manière itérative. C'est à dire que chaque fois qu'une fonctionnalité était implémentée, elle était testée à la main et de manière automatisée puis une nouvelle recherche et une nouvelle implémentation suivait.
:raw-latex:`\medskip`
Au fur et à mesures il a été possible de développer des solutions suivant les objectifs. Tout d'abord, un simple script permettait la communication entre RaspberryPi et Arduino, ensuite une interface web permettait de visualiser les données de ce Device. Suite à cela, le multiprocessing a été implémenté afin de gagner en performances et de ce fait, la communication entre les process a du être implémentée de manière concurrente. Ne connaissant pas le multiprocessing en python, il a fallu à nouveau effectuer des recherches. Finalement, l'interface web avec les configurations disponibles a pu être implémenté.
Integration continue
^^^^^^^^^^^^^^^^^^^^
Durant tout le processus de développement, des tests d'assurance qualité concernant la qualité du code ont été réalisés afin de garder le code lisible et compréhensible pour un autre développeur. Ces tests ont été automatisées grâce à l'utilisation de l'intégration continue. Il s'agit de réaliser des tests sur le code qui est mis en ligne sur un dépôt Git. Dans ce projet, le choix s'est porté sur Travis CI :raw-latex:`\cite{travis}`. Ce système de test d'intégration continue permet de configurer plusieurs choses dont le système d'exploitation sur lequel les tests sont menés et également quelles versions de python sont testées. Pour ce projet, le code est testé avec les versions 3.4, 3.5 et 3.6 de Python sur un os Linux.
Déploiement continu
^^^^^^^^^^^^^^^^^^^^
Suite à celà, nous avons choisi de créer une application installable au moyen du gestionnaire de dépendance intégré à Python, "Pip".
Afin de simplifier les déploiements, nous avons rajouté une étape à notre système d'intégration continue. Si tous les tests sont validés et que le commit est tagué avec une version qui est sous la forme 0.1.0, l'application est construite et déployée sur l'hébergeur de paquets Python Pypi.
De ce fait, beaucoup de temps a été gagné lors des tests et des déploiements étant donné qu'ils étaient réalisés automatiquement.
Difficultés rencontrés
======================
Plusieurs difficultés ont été rencontrées durant la réalisation de ce projet. En effet, n'ayant pas un cahier des charges basé sur des actions à effectuer mais sur des recherches à approfondir, il a fallu trouver des technologies compatibles et apprendre des nouvelles pratiques avant de pouvoir développer le projet.
:raw-latex:`\medskip`
Tout d'abord, il a fallu trouver quels utilitaires utiliser pour communiquer entre les différents composants de l'application.
Suite à cela, pour pouvoir améliorer les performances, il a été nécessaire d'implémenter du parallélisme. La communication inter-process n'étant pas toujours facile à cerner et réaliser de manière correcte, un certain temps à été utilisé à ces fins.
:raw-latex:`\medskip`
Il a fallu ensuite implémenter l'interface web complet et d'autres difficultés sont apparues. Il a été difficile de lier WebSockets, Processus et Arduinos. De plus, le stockage des configurations est resté longtemps un problème
:raw-latex:`\medskip`
Après avoir obtenu des résultats concluants concernant le fonctionnement de l'application sur nos systèmes respectifs, il a fallu réaliser l'installer pour le paquet.
L'emplacement des fichiers de configuration posé des problèmes car il a fallu trouver dans quels dossiers il était possible de créer un dossier sans privilèges. Nous avons décidé de créer un dossier caché situé dans le dossier personnel de l'utilisateur.
Résultats
=========
Grace à l'utilisation des technologies citées dans les section précédente, il a été possible de créer une interface web permettant la configuration et l'affichage des communications avec les Arduinos.
Communication
^^^^^^^^^^^^^
Comme expliqué au chapitre :raw-latex:`\ref{arduino}`, la communication est possible avec l'Arduino de manière simple.
:raw-latex:`\medskip`
Tout d'abord, l'Arduino s'annonce sur le port série jusqu'à ce que l'utilisateur lui indique qu'il est prêt.
:raw-latex:`\medskip`
Dès lors, il est possible de communiquer avec une console série ou via l'interface web de manière simple.
Interface
^^^^^^^^^
La figure $\ref{img/index.png}$ illustre la page d'accueil sans devices connectées.
:raw-latex:`\medskip`
La figure $\ref{img/indexWithArduino.png}$ illustre la page d'accueil avec un device connecté.
:raw-latex:`\medskip`
La figure $\ref{img/settings.png}$ illustre la page des paramètres disponibles. Il est possible de configurer des cartes (Uno, Mega, etc.), des capteurs et les devices possédant déjà une configuration.
:raw-latex:`\medskip`
La figure $\ref{img/settingsCard.png}$ illustre la page des paramètres des cartes. Comme aucune carte n'a encore été configurée, il est possible de créer une configuration.
:raw-latex:`\medskip`
La figure $\ref{img/settingsCardUno.png}$ illustre le formulaire de création de cartes.
:raw-latex:`\medskip`
La figure $\ref{img/settingsCardUno2.png}$ illustre l'affichage d'une configuration créée.
:raw-latex:`\medskip`
La figure $\ref{img/settingsCards.png}$ illustre la page des paramètres des cartes. Étant donné que des cartes ont été créées, les configurations sont listées.
:raw-latex:`\medskip`
La figure $\ref{img/communication.png}$ illustre la communication avec un Arduino. Il est possible d'observer qu'un capteur est configuré sur un port et qu'une sortie est également utilisée.
:raw-latex:`\medskip`
Les pages concernant les capteurs et les devices sont identiques.
Il est à noter que lors du branchement d'une nouvelle carte, si l'utilisateur souhaite visualiser ses données, le formulaire de création de configuration de device lui sera affiché. Une fois le device configuré, il sera possible d'interragir avec.
.. figure:: img/index.png
:width: 100%
:height: 30%
:alt: Page d'accueil
Page d'accueil
.. figure:: img/indexWithArduino.png
:width: 100%
:height: 30%
:alt: Page d'accueil avec Arduino
Page d'accueil avec Arduino
.. figure:: img/settings.png
:width: 100%
:height: 30%
:alt: Page des paramètres
Paramètres
.. figure:: img/settingsCard.png
:width: 100%
:height: 30%
:alt: Page des paramètres des cartes
Paramètres des cartes
.. figure:: img/settingsCardUno.png
:width: 100%
:height: 30%
:alt: Formulaire d'enregistrement de carte
Formulaire d'enregistrement de carte
.. figure:: img/settingsCardUno2.png
:width: 100%
:height: 30%
:alt: Configuration créée
Configuration pour la carte Uno
.. figure:: img/settingsCards.png
:width: 100%
:height: 30%
:alt: Liste des cartes configurées
Liste des cartes configurées
.. figure:: img/communication.png
:width: 100%
:height: 30%
:alt: Communication avec l'Arduino
Communication avec l'Arduino
:raw-latex:`\newpage`
Évolutions possibles
====================
Pour le moment, aucune protection n'a été implémentée. Tout utilisateur disposant de l'adresse du serveur peut y accéder et modifier les configurations. Ce projet étant destiné à un usage domestique dans un réseau isolé, nous n'avons pas mis un point d'honneur à développer cet aspect.
:raw-latex:`\medskip`
Il n'est également pas possible d'utiliser des capteurs qui ont besoin d'être activé au moyen d'une impulsion sur une entrée. Cet aspect reste relativement simple à développer étant donnée qu'il est possible d'activer des pins de sortie sur les Arduinos.
:raw-latex:`\medskip`
S'ajoute à cela l'impossibilité de lire les données de capteurs codées sur plus de 10 bits. Il n'est pour le moment pas possible d'aller lire des registres supplémentaires de l'Arduino pour récupérer l'entièreté d'une mesure. Si le temps l'avait permis, une solution à ce problème aurait été cherchée.
:raw-latex:`\medskip`
Si un capteur ne peut communiquer que via une connection série avec l'Arduino, il n'est également pas possible de l'utiliser. Ceci est également du au manque de temps.
Conclusion
==========
Au premier abord, le problème paraît simple à résoudre. Récupérer des données sur un Arduino, les afficher sur une page web, pouvoir configurer les devices. Cependant, plus le projet progresse et plus la difficulté augmente. Après avoir résolu des solutions pour les paliers précédents, il s'est parfois avéré que des problèmes avaient été crées pour lesquels il a fallu également trouver des solutions.
:raw-latex:`\medskip`
Durant tout le déroulement du projet, des avancées ont été réalisées mais presque toutes ont été ralenties par l'apparition de nouvelles difficulés.
:raw-latex:`\medskip`
À l'heure actuelle, l'application Arduinozore fonctionne et les objectifs principaux ont presque entièrement été respectés. Il est possible de lire les données de capteurs de manière générique, l'interface web permet l'affichage de ces données et le pilotage des sorties. L'Arduino est identifiable via un nom depuis l'application web grâce à son Hardware ID unique. De plus, les objectifs secondaires l'ont également été. Il est aussi possible de paramétrer les capteurs et cartes de manière simple. Les configurations sont également stockées. Cependant, le produit étant fonctionnel, il n'est pas terminé. Plusieurs améliorations, citées dans le chapitre précédant, sont encore possibles.
:raw-latex:`\medskip`
De plus, l'efficacité exacte d'une telle application est difficile à tester. En effet, tester que tous les messages envoyés de l'arduino sont affichés sur la page est compliqué. Il faudrait mettre en place des simulateurs et d'autres batteries de tests beaucoup plus compliquées.
:raw-latex:`\begin{thebibliography}{50}\section{Bibliographie}\label{bibliographie}`
:raw-latex:`\bibitem{arduino_home_page} Site web Arduino \textsl{25.04.2018}. \url{https://www.arduino.cc}`
:raw-latex:`\bibitem{raspberry_home_page} Site web RaspberryPi \textsl{25.04.2018}. \url{https://www.raspberrypi.org}`
:raw-latex:`\bibitem{github} Arduinozore sur github \textsl{26.01.2018}. \url{https://github.com/S-Amiral/arduinozore}`
:raw-latex:`\bibitem{technicalreport} TechnicalReport sur github \textsl{26.01.2018}. \url{https://github.com/73VW/TechnicalReport}`
:raw-latex:`\bibitem{wiki_websocket} WebSocket sur Wikipédia \textsl{26.01.2018}. \url{https://fr.wikipedia.org/wiki/WebSocket}`
:raw-latex:`\bibitem{binio} WebSocket sur Binio.io \textsl{26.01.2018}. \url{https://blog.bini.io/intro-websocket/}`
:raw-latex:`\bibitem{wiki_YAML} YAML sur Binio.io \textsl{26.01.2018}. \url{https://fr.wikipedia.org/wiki/YAML}`
:raw-latex:`\bibitem{wiki_crud} CRUD sur Wikipédia \textsl{26.01.2018}. \url{https://fr.wikipedia.org/wiki/CRUD}`
:raw-latex:`\bibitem{travis} Travis CI \textsl{26.01.2018}. \url{https://about.travis-ci.com}`
:raw-latex:`\end{thebibliography}`
|
Arduinozore
|
/Arduinozore-1.1.3.tar.gz/Arduinozore-1.1.3/doc/rapport/Rapport.rst
|
Rapport.rst
|
.. role:: raw-latex(raw)
:format: latex
L'installation est aisée. Le package se trouvant sur pypi, il suffit de l'installer via la commande
.. code-block:: bash
pip install arduinozore
Lors du premier lancement, si aucun dossier de configuration n'est trouvé, il est créé.
**Attention** Il est nécessaire d'avoir une connexion internet pour utiliser pip et lors du premier lancement de l'application. Des fichiers doivent être téléchargés depuis internet.
Pour afficher l'aide, la commande suivante est disponible
.. code-block:: bash
arduinozore --help
usage: arduinozore [-h] [-hp HTTP_PORT] [-hsp HTTPS_PORT] [-a path]
[--newconfig]
Arduinozore server
optional arguments:
-h, --help show this help message and exit
-hp HTTP_PORT, --http_port HTTP_PORT
Server http port. Default 8000
-hsp HTTPS_PORT, --https_port HTTPS_PORT
Server https port. Default 8001. Used for sockets too.
-a path, --arduino path
Path where arduino source code will be generated.
--newconfig Delete actual config and make a new one. Warning.
En cas de problème, il est possible de supprimer la configuration et la regénérer avec la commande
.. code-block:: bash
arduinozore --newconfig
Il est possible de spécifier les ports http et https. Par défaut les ports 8000 et 8001 sont utilisés. Pour ce faire, les options suivantes sont disponibles
.. code-block:: bash
arduinozore -hp 80 -hsp 443
Afin de récupérer le script arduino pour pouvoir le flasher, il est possible de l'obtenir avec l'option `-a` en donnant le path cible.
.. code-block:: bash
arduinozore -a /destination/path/for/arduino/script
Pour lancer l'application, il suffit d'exécuter
.. code-block:: bash
arduinozore
et de se rendre à l'adresse fournie dans le terminal.
**Attention**, si votre réseau domestique ne possède pas de serveur DNS, il sera nécessaire de remplacer l'adresse du serveur par son adresse IP afin de pouvoir y accéder.
Pour trouver cette adresse IP, la commande suivante suffit.
.. code-block:: bash
ifconfig
Par exemple, si lors du lancement, la chose suivante est affichée dans la console
.. code-block:: bash
/##########################################################################\
#
# # ##### ##### # # # # # #### ###### #### ##### ######
# # # # # # # # # ## # # # # # # # # #
# # # # # # # # # # # # # # # # # # # #####
####### ##### # # # # # # # # # # # # # ##### #
# # # # # # # # # # ## # # # # # # # #
# # # # ##### #### # # # #### ###### #### # # ######
\##########################################################################/
/##########################################################################\
Listening on: https://raspberry:8001
mais que vous ne possédez pas de dns, il faudra remplacer le nom "raspberry" par l'adresse IP du Raspberry Pi obtenue grâce à la commande "ifconfig".
:raw-latex:`\medskip`
Maintenant, il n'y a plus qu'à ouvrir un navigateur, se rendre à l'adresse correcte et effectuer quelques réglages et le tour est joué!
:raw-latex:`\medskip`
Tout d'abord, le navigateur risque de vous dire que le certificat n'a pas pu être vérifié. Étant donné qu'il est généré par l'application, il est autosigné. Il suffit donc de l'accepter tel quel.
Dès lors, la page d'accueil du site apparaît. Si des Arduinos sont connectés, il sont listés.
À présent, il est nécessaire de créer une configuration de carte en fonction du type d'Arduino que vous possédez. Cette création peut être atteinte dans les réglages.
Ensuite, il est nécessaire de configurer le ou les capteurs utilisés de la même manière que la ou les cartes.
:raw-latex:`\bigskip`
Il est maintenant possible de configurer l'Arduino et d'interagir avec lui! Bravo!
|
Arduinozore
|
/Arduinozore-1.1.3.tar.gz/Arduinozore-1.1.3/doc/manuelUtilisateur/ManuelUtilisateur.rst
|
ManuelUtilisateur.rst
|
Ardy (Arthur Hendy)
===================
.. image:: https://badge.fury.io/py/Ardy.svg
:target: https://pypi.org/project/Ardy/
.. image:: https://img.shields.io/pypi/dm/ardy.svg
:target: https://pypi.org/project/Ardy/
.. image:: https://travis-ci.org/avara1986/ardy.svg?branch=master
:target: https://travis-ci.org/avara1986/ardy
.. image:: https://coveralls.io/repos/github/avara1986/ardy/badge.svg?branch=master
:target: https://coveralls.io/github/avara1986/ardy?branch=master
.. image:: https://readthedocs.org/projects/ardy/badge/?version=latest
:target: http://ardy.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
.. image:: https://requires.io/github/avara1986/ardy/requirements.svg?branch=master
:target: https://requires.io/github/avara1986/ardy/requirements/?branch=master
:alt: Requirements Status
.. image:: https://pyup.io/repos/github/avara1986/ardy/shield.svg
:target: https://pyup.io/repos/github/avara1986/ardy/
:alt: Updates
.. image:: https://pyup.io/repos/github/avara1986/ardy/python-3-shield.svg
:target: https://pyup.io/repos/github/avara1986/ardy/
:alt: Python 3
Ardy is a toolkit to work with AWS Lambas and implement Continuous Integration.
AWS Lambda is a serverless compute service that runs your code in response to events and automatically manages the underlying compute resources for you. Alas,
AWS Lambda has a very bad GUI interfaces, especially if you work with teams and releases. You can't see at a glance
the triggers you have active, the resources of your AWS Lambda or have a version control.
With `Ardy` you can manage your AWS Lambda with a JSON config file stored in your VCS.
**IMPORTANT NOTE**: If you want to work with AWS Lambda, it's recommended read about it. `Ardy` helps and support you to manage your environments but doesn't performs "The black magic" for you.
Installation
------------
Install the latest Ardy release via pip:
.. code-block:: bash
pip install ardy
You may also install a specific version:
.. code-block:: bash
pip install ardy==0.0.1
Quickstart
----------
See the documentation
How to contrib
--------------
This project is build with `Git Flow <https://danielkummer.github.io/git-flow-cheatsheet/>`_. If you want to commit some
code use this pattern please:
.. image:: http://nvie.com/img/[email protected]
Extra: Why this name?
---------------------
.. code-block::
import operator
from nltk import FreqDist
from nltk.tokenize import RegexpTokenizer
from nltk.book import text6 # Book Monty Python Holy Grail
import requests
tokens = [f.lower() for f in text6]
result_holygrail = FreqDist(tokens)
# result_holygrail.most_common(42)
holygrail_top = [s[0] for s in sorted([(w, result_holygrail[w]) for w in set(tokens) if len(w) > 4 and result_holygrail[w] > 20], key=operator.itemgetter(1), reverse=True)]
tokenizer = RegexpTokenizer(r'\w+')
response = requests.get("http://www.angelfire.com/movies/closedcaptioned/meanlife.txt")
meanlife = response.text
tokens = tokenizer.tokenize(meanlife)
result_meanlife = FreqDist(tokens)
# result_meanlife.most_common(42)
meanlife_top = [s[0] for s in sorted([(w, result_meanlife[w]) for w in set(tokens) if len(w) > 4 and result_meanlife[w] > 20], key=operator.itemgetter(1), reverse=True)]
for i in range(0, 30):
print("{}: {} {}".format(i+1, holygrail_top[i], meanlife_top[i]))
print("{}: {}{}".format(i+1, holygrail_top[i][:2], meanlife_top[i][-2:]))
|
Ardy
|
/Ardy-0.0.6.tar.gz/Ardy-0.0.6/README.rst
|
README.rst
|
from __future__ import unicode_literals, print_function
import json
import os
from abc import ABCMeta
from ardy.config.exceptions import ArdyRequiredKeyError
from ardy.core.exceptions import ArdyLambdaNotExistsError
from ardy.core.exceptions import ArdyNoFileError, ArdyNoDirError, ArdyEnvironmentNotExistsError
from ardy.utils.log import logger
class BaseConfig(dict):
environment = None
__metaclass__ = ABCMeta
def __init__(self, *args, **kwargs):
super(BaseConfig, self).__init__(**kwargs)
def __getattr__(self, name, *args, **kwargs):
return self[name]
def __getitem__(self, key):
val = dict.__getitem__(self, key)
return val
def __setitem__(self, key, val):
dict.__setitem__(self, key, val)
def __repr__(self):
dictrepr = dict.__repr__(self)
return '%s(%s)' % (type(self).__name__, dictrepr)
def set_environment(self, environment=False):
logger.debug("Setting environment {}".format(environment))
self.environment = environment
def get_environment(self):
return self.environment
def update(self, *args, **kwargs):
for k, v in dict(*args, **kwargs).items():
self[k] = v
class GlobalConfig(BaseConfig):
"""Create the configuration needed to deploy a group of AWS lambda functions
"""
_DEFAULT_CONFIG_FILE_NAME = "config.json"
_REQUIRED_LAMBDAS_KEY = "lambdas"
_REQUIRED_KEYS = ("lambdas",)
deploy_environments = False
project_dir = ""
project_filename = ""
def __init__(self, *args, **kwargs):
super(GlobalConfig, self).__init__(*args, **kwargs)
self.set_projectdir(kwargs.get("path", False))
self.set_project_config_filename(kwargs.get("filename", False))
self._set_conf_from_file(environment=kwargs.get("environment", False))
for key in self._REQUIRED_KEYS:
if key not in self.keys():
raise ArdyRequiredKeyError("{} is required to create the configuration".format(key))
def set_projectdir(self, path=False):
self.project_dir = os.path.abspath(path or os.getcwd())
if self.project_dir and os.path.isdir(self.project_dir):
return True
raise ArdyNoDirError("Folder {} not exist".format(self.project_dir))
def get_projectdir(self):
return self.project_dir
def set_project_config_filename(self, filename=False):
self.project_filename = filename or self._DEFAULT_CONFIG_FILE_NAME
def get_project_config_filename(self):
return self.project_filename
def _get_config_file(self):
return os.path.join(self.get_projectdir(), self.get_project_config_filename())
def _set_conf_from_file(self, config_file=None, environment=False):
if not config_file:
config_file = self._get_config_file()
if os.path.isfile(config_file):
logger.debug("Loading configuration from file {}".format(config_file))
with open(config_file) as data_file:
config_dict = json.load(data_file)
self._set_conf_from_dict(config_dict=config_dict, environment=environment)
else:
raise ArdyNoFileError("File {} not exist".format(config_file))
def set_environment(self, environment=False):
if environment and environment not in self["deploy"]["deploy_environments"]:
raise ArdyEnvironmentNotExistsError("Environment {} not exists".format(environment))
self.environment = environment
def reload_conf(self):
self._set_conf_from_file()
def _set_conf_from_dict(self, config_dict, environment=False):
for key in config_dict:
self[key] = config_dict[key]
if environment:
self.set_environment(environment=environment)
self[self._REQUIRED_LAMBDAS_KEY] = [
LambdaConfig(awslambda, self.get_globals(), environment=self.get_environment()) for awslambda in
config_dict[self._REQUIRED_LAMBDAS_KEY]
]
def get_globals(self):
return {k: v for k, v in self.items() if k != "lambdas"}
def get_lambdas(self):
for awslambda in self["lambdas"]:
yield awslambda
def get_lambda_by_name(self, name):
for i in self.get_lambdas():
if i["FunctionName"] == name:
return i
raise ArdyLambdaNotExistsError("Lambda function {} not exist.".format(name))
def print_config(self):
print(json.dumps(self, indent=2))
class LambdaConfig(BaseConfig):
_DEPLOY_KEYS_BLACKLIST = ["path", "version", "filename", "aws_credentials", "deploy", "triggers",
"deploy_environments", "requirements", "environment", "lambdas_to_deploy",
"FunctionNameOrigin"]
def __init__(self, *args, **kwargs):
super(LambdaConfig, self).__init__(*args, **kwargs)
self.set_environment(kwargs.get("environment", False))
self._set_conf_from_dict(args[0], args[1])
environment_config = args[0].get("deploy_environments", {})
self["FunctionNameOrigin"] = self["FunctionName"]
if self.get_environment() and environment_config:
self._set_conf_from_dict(environment_config[self.get_environment()], self)
def _set_conf_from_dict(self, lambda_config, global_config):
aux_dict = self.merge_dicts(global_config, lambda_config)
for key in aux_dict:
self[key] = aux_dict[key]
def get_deploy_conf(self):
return {k: v for k, v in self.items() if k not in self._DEPLOY_KEYS_BLACKLIST}
def merge_dicts(self, x, y):
"""
if sys.version_info >= (3,5):
return {**x, **y}
else:
"""
z = x.copy()
z.update(y)
return z
class ConfigMixin(object):
def __init__(self, *args, **kwargs):
super(ConfigMixin, self).__init__()
logger.debug("[{}] loading config...".format(self.__class__, ))
self.config = GlobalConfig(*args, **kwargs)
|
Ardy
|
/Ardy-0.0.6.tar.gz/Ardy-0.0.6/ardy/config/__init__.py
|
__init__.py
|
from __future__ import unicode_literals, print_function
import json
import os
from botocore.exceptions import ClientError
from ardy.config import ConfigMixin
from ardy.core.build import Build
from ardy.core.triggers import get_trigger
from ardy.utils.aws import AWSCli
from ardy.utils.log import logger
class Deploy(ConfigMixin):
build = None
lambdas_to_deploy = []
def __init__(self, *args, **kwargs):
"""
:param args:
:param kwargs:
* path: string. from ConfigMixin. Required
* filename: string. from ConfigMixin. Required
* environment: string. One of elements of config["deploy"]["deploy_environments"] if its defined
* config: dict. Required
* lambdas_to_deploy: list. Optional
"""
self.config = kwargs.get("config", False)
if not self.config:
super(Deploy, self).__init__(*args, **kwargs)
# If run deploy from command line, config is setted before environment requested by argparser. Need to reset
# Environment
self.config.set_environment(kwargs.get("environment"))
lambdas_to_deploy = kwargs.get("lambdas_to_deploy", [])
if type(lambdas_to_deploy) is not list:
lambdas_to_deploy = [lambdas_to_deploy, ]
self.lambdas_to_deploy = lambdas_to_deploy
self.awslambda = AWSCli(config=self.config).get_lambda_client()
self.awss3 = AWSCli(config=self.config).get_s3_resource()
self.build = Build(config=self.config)
def run(self, src_project=None, path_to_zip_file=None):
"""Run deploy the lambdas defined in our project.
Steps:
* Build Artefact
* Read file or deploy to S3. It's defined in config["deploy"]["deploy_method"]
* Reload conf with deploy changes
* check lambda if exist
* Create Lambda
* Update Lambda
:param src_project: str. Name of the folder or path of the project where our code lives
:param path_to_zip_file: str.
:return: bool
"""
if path_to_zip_file:
code = self.set_artefact_path(path_to_zip_file)
elif not self.config["deploy"].get("deploy_file", False):
code = self.build_artefact(src_project)
else:
code = self.set_artefact_path(self.config["deploy"].get("deploy_file"))
self.set_artefact(code=code)
# Reload conf because each lambda conf need to read again the global conf
self.config.reload_conf()
self.deploy()
return True
def set_artefact_path(self, path_to_zip_file):
"""
Set the route to the local file to deploy
:param path_to_zip_file:
:return:
"""
self.config["deploy"]["deploy_file"] = path_to_zip_file
return {'ZipFile': self.build.read(self.config["deploy"]["deploy_file"])}
def set_artefact(self, code):
"""
:param code: dic. it must be with this shape
{'ZipFile': } or {'S3Bucket': deploy_bucket, 'S3Key': s3_keyfile, }
:return:
"""
self.config["Code"] = code
def build_artefact(self, src_project=None):
"""Run deploy the lambdas defined in our project.
Steps:
* Build Artefact
* Read file or deploy to S3. It's defined in config["deploy"]["deploy_method"]
:param src_project: str. Name of the folder or path of the project where our code lives
:return: bool
"""
path_to_zip_file = self.build.run(src_project or self.config.get_projectdir())
self.set_artefact_path(path_to_zip_file)
deploy_method = self.config["deploy"]["deploy_method"]
if deploy_method == "S3":
deploy_bucket = self.config["deploy"]["deploy_bucket"]
bucket = self.awss3.Bucket(deploy_bucket)
try:
self.awss3.meta.client.head_bucket(Bucket=deploy_bucket)
except ClientError as e:
if e.response['Error']['Code'] == "404" or e.response['Error']['Code'] == "NoSuchBucket":
region = self.config.get("aws_credentials", {}).get("region", None)
logger.info(
"Bucket not exist. Creating new one with name {} in region {}".format(deploy_bucket, region))
bucket_conf = {}
if region:
bucket_conf = {"CreateBucketConfiguration": {'LocationConstraint': region}}
bucket.wait_until_not_exists()
bucket.create(**bucket_conf)
bucket.wait_until_exists()
else:
# TODO: handle other errors there
pass
s3_keyfile = self.config["deploy"]["deploy_file"].split(os.path.sep)[-1]
bucket.put_object(
Key=s3_keyfile,
Body=self.build.read(self.config["deploy"]["deploy_file"])
)
code = {'S3Bucket': deploy_bucket, 'S3Key': s3_keyfile, }
elif deploy_method == "FILE":
code = {'ZipFile': self.build.read(self.config["deploy"]["deploy_file"])}
else:
raise Exception("No deploy_method in config")
return code
def deploy(self):
"""Upload code to AWS Lambda. To use this method, first, must set the zip file with code with
`self.set_artefact(code=code)`. Check all lambdas in our config file or the functions passed in command line
and exist in our config file. If the function is upload correctly, update/create versions, alias and
triggers
:return: True
"""
lambdas_deployed = []
for lambda_funcion in self.config.get_lambdas():
start_deploy = not len(self.lambdas_to_deploy) or \
lambda_funcion["FunctionNameOrigin"] in self.lambdas_to_deploy
if start_deploy:
lambdas_deployed.append(lambda_funcion["FunctionName"])
conf = lambda_funcion.get_deploy_conf()
response = self.remote_get_lambda(**conf)
if response:
remote_conf = response["Configuration"]
# TODO: Diferences sometimes not return all values, check it!
logger.info("Diferences:")
diffkeys = [k for k in remote_conf if
conf.get(k, False) != remote_conf.get(k, True) and k not in ['Code', ]]
for k in diffkeys:
logger.info((k, ':', conf.get(k, ""), '->', remote_conf.get(k, "")))
logger.info("START to update funcion {}".format(conf["FunctionName"]))
self.remote_update_conf_lambada(**conf)
result = self.remote_update_code_lambada(**conf)
logger.debug("Funcion {} updated {}".format(conf["FunctionName"], result))
else:
logger.info("START to create funcion {}".format(lambda_funcion["FunctionName"]))
result = self.remote_create_lambada(**conf)
logger.debug("Funcion {} created {}".format(conf["FunctionName"], result))
if self.is_client_result_ok(result):
# Check and publish version
version = "LATEST"
if self.config["deploy"].get("use_version", False):
logger.info("Publish new version of {} with conf {}".format(
lambda_funcion["FunctionName"],
json.dumps(conf, indent=4, sort_keys=True)
))
result = self.remote_publish_version(**conf)
version = result["Version"]
logger.info("Published version {}: {}".format(
version,
json.dumps(result, indent=4, sort_keys=True)
))
# Check and publish alias
if self.config["deploy"].get("use_alias", False):
alias_conf = {
"FunctionName": conf["FunctionName"],
"Description": conf["Description"],
"FunctionVersion": version,
}
if self.config.get_environment():
alias_conf.update({"Name": self.config.get_environment()})
else:
alias_conf.update({"Name": conf["FunctionName"]})
logger.info("Update alias of {} with conf {}".format(
lambda_funcion["FunctionName"],
json.dumps(alias_conf, indent=4, sort_keys=True)
))
result = self.remote_update_alias(**alias_conf)
logger.info("Updated alias {}: {}".format(conf["FunctionName"],
json.dumps(result, indent=4, sort_keys=True)
))
# Check and publish triggers
logger.info("Updating Triggers for fuction {}".format(lambda_funcion["FunctionName"]))
if lambda_funcion.get("triggers", False):
for trigger in lambda_funcion["triggers"].keys():
trigger_object = get_trigger(trigger, lambda_funcion, result["FunctionArn"])
trigger_object.put()
if lambdas_deployed:
logger.info("Deploy finished. Created/updated lambdas {}".format(", ".join(lambdas_deployed)))
else:
logger.info("No lambdas found to deploy")
# TODO: check errors to return correct value
return True
@staticmethod
def is_client_result_ok(result):
return result['ResponseMetadata']['HTTPStatusCode'] in (201, 200)
def remote_get_lambda(self, **kwargs):
response = False
try:
response = self.awslambda.get_function(
FunctionName=kwargs["FunctionName"],
)
tags = response.get("Tags", False)
if tags:
response["Configuration"]["Tags"] = tags
except ClientError as e:
if e.response['Error']['Code'] == "ResourceNotFoundException":
return False
else:
# TODO: handle other errors there
pass
return response
def remote_list_lambdas(self):
response = self.awslambda.list_functions(
MaxItems=100
)
return response
def remote_create_lambada(self, **kwargs):
response = self.awslambda.create_function(**kwargs)
return response
def remote_update_code_lambada(self, **kwargs):
conf = {"FunctionName": kwargs["FunctionName"]}
conf.update(kwargs["Code"])
response = self.awslambda.update_function_code(**conf)
return response
def remote_update_conf_lambada(self, **kwargs):
conf = {k: v for k, v in kwargs.items() if k not in ["Code", "Tags", "Publish"]}
response = self.awslambda.update_function_configuration(**conf)
return response
def remote_publish_version(self, **kwargs):
conf = {k: v for k, v in kwargs.items() if k in ["FunctionName", "Description"]}
response = self.awslambda.publish_version(**conf)
return response
def remote_update_alias(self, **kwargs):
conf = kwargs
try:
logger.info("Update alias {} for function {}"
" with version {}".format(conf["Name"],
conf["FunctionName"],
conf["FunctionVersion"]))
response = self.awslambda.update_alias(**conf)
except ClientError as e:
if e.response['Error']['Code'] == "ResourceNotFoundException":
logger.info("Alias {} not exist for function {}. "
"Creating new one with version {}".format(conf["Name"],
conf["FunctionName"],
conf["FunctionVersion"]))
response = self.awslambda.create_alias(**conf)
else:
# TODO: handle other errors there
pass
return response
|
Ardy
|
/Ardy-0.0.6.tar.gz/Ardy-0.0.6/ardy/core/deploy/deploy.py
|
deploy.py
|
from __future__ import unicode_literals, print_function
import argparse
import sys
import traceback
from ardy.config import GlobalConfig
from ardy.core.build import Build
from ardy.core.deploy import Deploy
from ardy.utils.log import logger
class Command(object):
config = None
parser = None
args = []
def __init__(self, *args, **kwargs):
arguments = kwargs.get("arguments", False)
self.exit_at_finish = kwargs.get("exit_at_finish", True)
if not arguments:
arguments = sys.argv[1:]
self.parser = self.init_config(arguments)
commands = self.parser.add_subparsers(title="Commands", description='Available commands', dest='command_name')
# Add deploy commands
parser_deploy = commands.add_parser('deploy', help='Upload functions to AWS Lambda')
parser_deploy.add_argument("lambdafunctions", default="_ALL_", nargs='*', type=str, help='Lambda(s) to deploy')
parser_deploy.add_argument("-z", "--zipfile", help="Path and filename of artefact to deploy")
environments = self.config["deploy"].get("deploy_environments", [])
if environments:
parser_deploy.add_argument("environment", choices=environments, type=str,
help='Environment where deploy: {}'.format(environments))
# Add invoke commands
parser_invoke = commands.add_parser('invoke', help='Invoke a functions from AWS Lambda')
parser_invoke.add_argument("-l", "--lambda-function", help="lambda")
# Add build commands
parser_build = commands.add_parser('build',
help='Create an artefact and Upload to S3 if S3 is configured (See config)')
parser_build.add_argument("-r", "--requirements", help="Path and filename of the python project")
self.args = self.parser.parse_args(arguments)
try:
result = self.parse_commandline()
if result:
self.exit_ok("OK")
except Exception as e:
# traceback = sys.exc_info()[2]
logger.error(traceback.format_exc())
self.exit_with_error("ERROR")
@property
def parser_base(self):
parser = argparse.ArgumentParser(description='Ardy. AWS Lambda Toolkit')
parser.add_argument("-f", "--conffile", help="Name to the project config file")
parser.add_argument("-p", "--project", help="Project path")
return parser
def init_config(self, arguments):
# TODO: refactor this method... sooo ugly :S
parser = self.parser_base
parser.add_argument('args', nargs=argparse.REMAINDER)
base_parser = parser.parse_args(arguments)
params = {}
if getattr(base_parser, "project", False) and base_parser.project is not None:
params["path"] = base_parser.project
if getattr(base_parser, "conffile", False) and base_parser.conffile is not None:
params["filename"] = base_parser.conffile
self.config = GlobalConfig(**params)
return self.parser_base
def parse_commandline(self):
params = {}
run_params = {}
result = False
if self.args.command_name == "deploy":
if self.args.lambdafunctions and self.args.lambdafunctions is not "_ALL_":
params["lambdas_to_deploy"] = self.args.lambdafunctions
if getattr(self.args, "environment", False):
params["environment"] = self.args.environment
if getattr(self.args, "zipfile", False):
run_params["path_to_zip_file"] = self.args.zipfile
deploy = Deploy(config=self.config, **params)
result = deploy.run(**run_params)
elif self.args.command_name == "invoke":
pass
elif self.args.command_name == "build":
if getattr(self.args, "requirements", False):
run_params["requirements"] = self.args.requirements
build = Build(config=self.config)
result = build.run(**params)
else:
self.parser.print_help()
return result
def exit_with_error(self, msg=""):
self.print_error(msg)
if self.exit_at_finish:
sys.exit(2)
def exit_ok(self, msg=""):
self.print_ok(msg)
if self.exit_at_finish:
sys.exit(0)
@staticmethod
def print_ok(msg=""):
print('\033[92m\033[1m ' + msg + ' \033[0m\033[0m')
@staticmethod
def print_error(msg=""):
print('\033[91m\033[1m ' + msg + ' \033[0m\033[0m')
if __name__ == '__main__':
cmd = Command(arguments=sys.argv[1:])
|
Ardy
|
/Ardy-0.0.6.tar.gz/Ardy-0.0.6/ardy/core/cmd/main.py
|
main.py
|
from __future__ import unicode_literals, print_function
import json
from abc import ABCMeta, abstractmethod
from botocore.exceptions import ClientError
from ardy.core.triggers.exceptions import ArdyNoTriggerConfError
from ardy.utils.aws import AWSCli
class Trigger(object):
__metaclass__ = ABCMeta
_DEPLOY_KEYS_WHITELIST = []
_LAMBDA_ARN_KEY = None
trigget_type = None
get_awsservice_method = None
awsservice_put_method = None
def __init__(self, *args, **kwargs):
self.lambda_function_arn = kwargs["lambda_function_arn"]
self.lambda_conf = kwargs["lambda_conf"]
self.client = self.set_client()
self.awslambda = AWSCli(config=self.lambda_conf).get_lambda_client()
def get_triggers(self):
trigger_conf = self.lambda_conf.get("triggers", {}).get(self.trigget_type)
if not len(trigger_conf):
raise ArdyNoTriggerConfError(
"Not exists conf for lambda {} and trigger {}".format(self.lambda_function_arn, self.trigget_type))
return trigger_conf
def get_trigger_conf(self, index):
trigger_conf = self.get_triggers()[index]
return trigger_conf
def get_deploy_conf(self, trigger_conf):
# TODO: Refactor like conf and lambda conf?
conf = {k: v for k, v in trigger_conf.items() if k in self._DEPLOY_KEYS_WHITELIST}
return conf
def set_client(self):
return self.set_aws_class()
def set_aws_class(self, *args, **kwargs):
return getattr(AWSCli(config=self.lambda_conf), self.get_awsservice_method)()
@abstractmethod
def put(self, *args, **kwargs):
return getattr(self.client, self.awsservice_put_method)(*args, **kwargs)
def lambda_exist_policy(self, function_name, StatementId):
try:
response = self.awslambda.get_policy(FunctionName=function_name)
except ClientError as e:
if e.response['Error']['Code'] == "ResourceNotFoundException":
return False
else:
# TODO: handle other errors there
return False
policies = json.loads(response["Policy"])
for policy in policies["Statement"]:
if policy["Sid"] == StatementId:
return True
return False
|
Ardy
|
/Ardy-0.0.6.tar.gz/Ardy-0.0.6/ardy/core/triggers/driver.py
|
driver.py
|
from __future__ import unicode_literals, print_function
import datetime
import os
import zipfile
from builtins import str
from shutil import copy2
from tempfile import mkdtemp
import pip
from ardy.config import ConfigMixin
from ardy.core.exceptions import ArdyNoFileError
from ardy.utils.log import logger
class Build(ConfigMixin):
src_path = ""
def __init__(self, *args, **kwargs):
self.config = kwargs.get("config", False)
if not self.config:
super(Build, self).__init__(*args, **kwargs)
def mkdir(self, path):
path = os.path.join(self.config.get_projectdir(), path)
if not os.path.exists(path):
os.makedirs(path)
return True
return False
@staticmethod
def read(path, loader=None):
with open(path, "rb") as fh:
if not loader:
return fh.read()
return loader(fh.read())
@staticmethod
def timestamp(fmt='%Y-%m-%d-%H%M%S'):
now = datetime.datetime.utcnow()
return now.strftime(fmt)
def create_artefact(self, src, dest, filename):
if not os.path.isabs(dest):
dest = os.path.join(self.config.get_projectdir(), dest)
dest = os.path.abspath(dest)
if not os.path.isabs(src):
src = os.path.join(self.config.get_projectdir(), src)
relroot = os.path.abspath(src)
output = os.path.join(dest, filename)
excluded_folders = ["dist", ]
excluded_files = []
if not os.path.isdir(src) and not os.path.isfile(src):
raise ArdyNoFileError("{} not exists".format(src))
with zipfile.ZipFile(output, 'a', compression=zipfile.ZIP_DEFLATED) as zf:
for root, subdirs, files in os.walk(src):
excluded_dirs = []
for subdir in subdirs:
for excluded in excluded_folders:
if subdir.startswith(excluded):
excluded_dirs.append(subdir)
for excluded in excluded_dirs:
subdirs.remove(excluded)
try:
dir_path = os.path.relpath(root, relroot)
dir_path = os.path.normpath(
os.path.splitdrive(dir_path)[1]
)
while dir_path[0] in (os.sep, os.altsep):
dir_path = dir_path[1:]
dir_path += '/'
zf.getinfo(dir_path)
except KeyError:
zf.write(root, dir_path)
for filename in files:
if filename not in excluded_files:
filepath = os.path.join(root, filename)
if os.path.isfile(filepath):
arcname = os.path.join(
os.path.relpath(root, relroot), filename)
try:
zf.getinfo(arcname)
except KeyError:
zf.write(filepath, arcname)
return output
def copytree(self, src, dst, symlinks=False, ignore=None):
if not os.path.exists(dst):
os.makedirs(dst)
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
self.copytree(s, d, symlinks, ignore)
else:
if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1:
copy2(s, d)
def set_src_path(self, src_folder):
self.src_path = os.path.abspath(os.path.join(self.config.get_projectdir(), src_folder))
def get_src_path(self):
return self.src_path
def run(self, src_folder, requirements="requirements.txt", local_package=None):
"""Builds the file bundle.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param str local_package:
The path to a local package with should be included in the deploy as
well (and/or is not available on PyPi)
"""
self.set_src_path(src_folder)
if not os.path.isdir(self.get_src_path()):
raise ArdyNoFileError("File {} not exist".format(self.get_src_path()))
# Get the absolute path to the output directory and create it if it doesn't
# already exist.
dist_directory = 'dist'
path_to_dist = os.path.join(self.get_src_path(), dist_directory)
self.mkdir(path_to_dist)
# Combine the name of the Lambda function with the current timestamp to use
# for the output filename.
output_filename = "{0}.zip".format(self.timestamp())
path_to_temp = mkdtemp(prefix='aws-lambda')
self.pip_install_to_target(path_to_temp,
requirements=requirements,
local_package=local_package)
if os.path.isabs(src_folder):
src_folder = src_folder.split(os.sep)[-1]
self.copytree(self.get_src_path(), os.path.join(path_to_temp, src_folder))
# Zip them together into a single file.
# TODO: Delete temp directory created once the archive has been compiled.
path_to_zip_file = self.create_artefact(path_to_temp, path_to_dist, output_filename)
return path_to_zip_file
def _install_packages(self, path, packages):
"""Install all packages listed to the target directory.
Ignores any package that includes Python itself and python-lambda as well
since its only needed for deploying and not running the code
:param str path:
Path to copy installed pip packages to.
:param list packages:
A list of packages to be installed via pip.
"""
def _filter_blacklist(package):
blacklist = ["-i", "#", "Python==", "ardy=="]
return all(package.startswith(entry.encode()) is False for entry in blacklist)
filtered_packages = filter(_filter_blacklist, packages)
# print([package for package in filtered_packages])
for package in filtered_packages:
package = str(package, "utf-8")
if package.startswith('-e '):
package = package.replace('-e ', '')
logger.info('Installing {package}'.format(package=package))
pip.main(['install', package, '-t', path, '--ignore-installed', '-q'])
def pip_install_to_target(self, path, requirements="", local_package=None):
"""For a given active virtualenv, gather all installed pip packages then
copy (re-install) them to the path provided.
:param str path:
Path to copy installed pip packages to.
:param str requirements:
If set, only the packages in the requirements.txt file are installed.
The requirements.txt file needs to be in the same directory as the
project which shall be deployed.
Defaults to false and installs all pacakges found via pip freeze if
not set.
:param str local_package:
The path to a local package with should be included in the deploy as
well (and/or is not available on PyPi)
"""
packages = []
if not requirements:
logger.debug('Gathering pip packages')
# packages.extend(pip.operations.freeze.freeze())
pass
else:
requirements_path = os.path.join(self.get_src_path(), requirements)
logger.debug('Gathering packages from requirements: {}'.format(requirements_path))
if os.path.isfile(requirements_path):
data = self.read(requirements_path)
packages.extend(data.splitlines())
else:
logger.debug('No requirements file in {}'.format(requirements_path))
if local_package is not None:
if not isinstance(local_package, (list, tuple)):
local_package = [local_package]
for l_package in local_package:
packages.append(l_package)
self._install_packages(path, packages)
|
Ardy
|
/Ardy-0.0.6.tar.gz/Ardy-0.0.6/ardy/core/build/build.py
|
build.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.