Skip to content

Commit

Permalink
Merge pull request #6 from Postcard/v0.2.0
Browse files Browse the repository at this point in the history
V0.2.0
  • Loading branch information
benoitguigal committed Apr 20, 2015
2 parents 91eb834 + 3bd59ab commit d9cea50
Show file tree
Hide file tree
Showing 10 changed files with 161 additions and 139 deletions.
9 changes: 5 additions & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -61,20 +61,21 @@ RUN pip install ZODB==4.1.0
RUN pip install ZODB3==3.11.0
RUN pip install pytz==2015.2
RUN pip install celery==3.1.17
RUN pip install Django==1.8

RUN wget --no-check-certificate https://github.com/benoitguigal/python-epson-printer/archive/v1.6.zip
RUN unzip v1.6.zip
RUN cd python-epson-printer-1.6 && python setup.py install

ADD figureraspbian /figure/figureraspbian
WORKDIR /figure
RUN mkdir -p media/images media/snapshots media/tickets resources
RUN mkdir -p /var
RUN cd /var && mkdir -p run log data images snapshots tickets
RUN mkdir -p media/images media/snapshots media/tickets resources
RUN mkdir -p /var/log /var/run /var/db /var/images /var/snapshots /var/tickets /var/rabbitmq


ENV LANG C.UTF-8
ENV C_FORCE_ROOT true
ENV DB_PATH /var/data/db.fs
ENV DB_PATH /var/db/db.fs
ENV FIGURE_DIR /figure/figureraspbian
ENV IMAGE_DIR /var/images
ENV PHANTOMJS_PATH /phantomjs-linux-armv6l-master/phantomjs-1.9.0-linux-armv6l/bin/phantomjs
Expand Down
2 changes: 1 addition & 1 deletion figureraspbian/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def get_listener():
logger.info("Initializing Figure application...")

# Make sure database is correctly initialized
with managed(Database(settings.ENVIRONMENT)) as db:
with managed(Database()) as db:
if utils.internet_on():
logging.info("Got an internet connection. Initializing database...")
db.update()
Expand Down
52 changes: 16 additions & 36 deletions figureraspbian/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class ApiException(Exception):

def get_installation():
url = "%s/resiniodevices/%s/" % (settings.API_HOST, settings.RESIN_DEVICE_UUID)
r = session.get(url=url, timeout=6)
r = session.get(url=url, timeout=10)
if r.status_code == 200:
return json.loads(r.text)['active_installation']
else:
Expand All @@ -33,7 +33,7 @@ def get_installation():

def get_scenario(scenario_id):
url = "%s/scenarios/%s/?fields=name,ticket_template" % (settings.API_HOST, scenario_id)
r = session.get(url=url, timeout=3)
r = session.get(url=url, timeout=10)
if r.status_code == 200:
return json.loads(r.text)
else:
Expand All @@ -47,7 +47,7 @@ def download(url, path):
local_name = url2name(url)
req = urllib2.Request(url)
try:
r = urllib2.urlopen(req)
r = urllib2.urlopen(req, timeout=10)
if r.url != url:
# if we were redirected, the real file name we take from the final URL
local_name = url2name(r.url)
Expand All @@ -59,43 +59,23 @@ def download(url, path):
raise ApiException('Failed downloading resource %s with error %s' % (url, e.msg))


def create_random_text_selection(variable, value):
url = "%s/randomtextselections/" % settings.API_HOST
data = {
'variable': variable,
'value': value
}
r = session.post(url, data=data, timeout=10)
if r.status_code == 201:
return json.loads(r.text)['id']
else:
raise ApiException("Failed creating ticket with message %s" % r.text)


def create_random_image_selection(variable, value):
url = "%s/randomimageselections/" % settings.API_HOST
data = {
'variable': variable,
'value': value
}
r = session.post(url, data=data, timeout=10)
if r.status_code == 201:
return json.loads(r.text)['id']
else:
raise ApiException("Failed creating ticket with message %s" % r.text)
def create_ticket(ticket):
url = "%s/tickets/" % settings.API_HOST
files = {'snapshot': open(ticket['snapshot'], 'rb'), 'ticket': open(ticket['ticket'], 'rb')}

# serialize random selections to be posted as a multipart/form-data
def serialize(selections):
serialized = ','.join(['%s:%s' % (selection[0], selection[1]['id']) for selection in selections])
return serialized

def create_ticket(installation, snapshot, ticket, datetime, code, random_text_selections, random_image_selections):
url = "%s/tickets/" % settings.API_HOST
files = {'snapshot': open(snapshot, 'rb'), 'ticket': open(ticket, 'rb')}
data = {
'datetime': datetime,
'code': code,
'random_text_selections': random_text_selections,
'random_image_selections': random_image_selections,
'installation': installation
'datetime': ticket['dt'],
'code': ticket['code'],
'rdm_text_selections': serialize(ticket['random_text_selections']),
'rdm_image_selections': serialize(ticket['random_image_selections']),
'installation': ticket['installation']
}
r = session.post(url, files=files, data=data, timeout=15)
r = session.post(url, files=files, data=data, timeout=20)
if r.status_code == 201:
return json.loads(r.text)['id']
else:
Expand Down
14 changes: 6 additions & 8 deletions figureraspbian/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,10 @@ def managed(database):

class Database(persistent.Persistent):

def __init__(self, env):
def __init__(self):
storage = ClientStorage.ClientStorage(settings.ZEO_SOCKET)
self.db = DB(storage)
self.data = None
self.env = env

def open(self):
self.data = self.db.open().root()
Expand All @@ -54,15 +53,14 @@ def update(self):
api.download(image['media'], settings.IMAGE_DIR)
ticket_css_url = "%s/%s" % (settings.API_HOST, 'static/css/ticket.css')
api.download(ticket_css_url, settings.RESOURCE_DIR)
self.data[self.env] = {}
self.data[self.env]['installation'] = installation
self.data[self.env]['scenario'] = scenario
self.data['installation'] = installation
self.data['scenario'] = scenario
transaction.commit()
except Exception:
logger.error(traceback.format_exc())

def is_initialized(self):
return self.env in self.data
return 'installation' in self.data

def check_initialized(func):
def check(self):
Expand All @@ -73,11 +71,11 @@ def check(self):

@check_initialized
def installation(self):
return self.data[self.env]['installation']
return self.data['installation']

@check_initialized
def scenario(self):
return self.data[self.env]['scenario']
return self.data['scenario']

@check_initialized
def ticket_template(self):
Expand Down
132 changes: 68 additions & 64 deletions figureraspbian/processus.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,10 @@
import traceback

from selenium import webdriver
import tasks

from .ticketrenderer import TicketRenderer
from . import devices, settings
from . import devices, settings, tasks
from .db import Database, managed
from .utils import internet_on


phantom_js = webdriver.PhantomJS(executable_path=settings.PHANTOMJS_PATH)
Expand All @@ -26,75 +24,81 @@


def run():
with managed(Database(settings.ENVIRONMENT)) as db:
with managed(Database()) as db:
try:
# check if installation is not finished
end = datetime.strptime(db.installation()['end'], '%Y-%m-%dT%H:%M:%SZ')
end = end.replace(tzinfo=pytz.UTC)

if end > datetime.now(pytz.timezone(settings.TIMEZONE)):

# Get installation id
installation = db.installation()['id']

# Initialize blinking task
blinking_task = None
# Set Output to False
devices.OUTPUT.set(True)

# Take a snapshot
start = time.time()
snapshot = devices.CAMERA.capture(installation)
end = time.time()
logger.info('Snapshot capture successfully executed in %s seconds', end - start)
# Start blinking
blinking_task = devices.OUTPUT.blink()

# Render ticket
start = time.time()
t = db.ticket_template()
renderer = TicketRenderer(t['html'], t['text_variables_objects'], t['image_variables_objects'],
t['images_objects'])
html, dt, code, random_text_selections, random_image_selections = \
renderer.render(installation, snapshot)

with open(settings.TICKET_HTML_PATH, 'wb+') as ticket:
ticket.write(html)
url = "file://%s" % settings.TICKET_HTML_PATH
phantom_js.get(url)
ticket = join(settings.TICKET_DIR, basename(snapshot))
phantom_js.save_screenshot(ticket)
end = time.time()
logger.info('Ticket successfully rendered in %s seconds', end - start)

# Print ticket
start = time.time()
devices.PRINTER.print_ticket(ticket)
end = time.time()
logger.info('Ticket successfully printed in %s seconds', end - start)

# Stop blinking
blinking_task.terminate()

# Set Output to True
devices.OUTPUT.set(False)

# add task upload ticket task to the queue
tasks.create_ticket.delay(installation, snapshot, ticket, dt, code, random_text_selections,
random_image_selections)
else:
logger.warning("Current installation has ended. Skipping processus execution")
# check if installation is not finished
end = datetime.strptime(db.installation()['end'], '%Y-%m-%dT%H:%M:%SZ')
end = end.replace(tzinfo=pytz.UTC)

if end > datetime.now(pytz.timezone(settings.TIMEZONE)):

# Retrieve necessary information from database
installation = db.installation()['id']
ticket_template = db.ticket_template()

# Initialize blinking task
blinking_task = None
# Set Output to False
devices.OUTPUT.set(True)

# Take a snapshot
start = time.time()
snapshot = devices.CAMERA.capture(installation)
end = time.time()
logger.info('Snapshot capture successfully executed in %s seconds', end - start)
# Start blinking
blinking_task = devices.OUTPUT.blink()

# Render ticket
start = time.time()
renderer = TicketRenderer(ticket_template['html'],
ticket_template['text_variables_objects'],
ticket_template['image_variables_objects'],
ticket_template['images_objects'])
html, dt, code, random_text_selections, random_image_selections = \
renderer.render(installation, snapshot)

with open(settings.TICKET_HTML_PATH, 'wb+') as ticket:
ticket.write(html)
url = "file://%s" % settings.TICKET_HTML_PATH
phantom_js.get(url)
ticket = join(settings.TICKET_DIR, basename(snapshot))
phantom_js.save_screenshot(ticket)
end = time.time()
logger.info('Ticket successfully rendered in %s seconds', end - start)

# Print ticket
start = time.time()
devices.PRINTER.print_ticket(ticket)
end = time.time()
logger.info('Ticket successfully printed in %s seconds', end - start)

# Stop blinking
blinking_task.terminate()

# Set Output to True
devices.OUTPUT.set(False)

# add task upload ticket task to the queue
ticket = {
'installation': installation,
'snapshot': snapshot,
'ticket': ticket,
'dt': dt,
'code': code,
'random_text_selections': random_text_selections,
'random_image_selections': random_image_selections
}
tasks.create_ticket.delay(ticket)
else:
logger.warning("Current installation has ended. Skipping processus execution")
except Exception as e:
logger.error(e.message)
logger.error(traceback.format_exc())
finally:
if 'blinking_task' in locals():
if blinking_task is not None:
blinking_task.terminate()
# update db
if internet_on():
logger.info("Got internet connection. Updating database...")
db.update()
else:
logger.warning("No internet connection. Could not update database")

Expand Down
2 changes: 1 addition & 1 deletion figureraspbian/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def get_env_setting(setting, default=None):
TIMEZONE = get_env_setting('TIMEZONE', 'Europe/Paris')

# Countdown for retrying uploading a ticket
RETRY_DELAY = get_env_setting('RETRY_DELAY', 60)
RETRY_DELAY = get_env_setting('RETRY_DELAY', 3600)

# Camera type
CAMERA_TYPE = get_env_setting('CAMERA_TYPE', 'CANON')
Expand Down
Loading

0 comments on commit d9cea50

Please sign in to comment.