sensor_pin = 'P9_40'
extreme_lo = ['dark','inky','shadowed','midnight''black','sinister','dour','glowering','glum','moody','morose','saturnine','sour','sullen','benighted','obscure','blue','dingy','disconsolate','dismal','gloomy','grim','sorry','drab','drear','dreary','colored','coloured','dark-skinned','non-white','depressing','dispiriting']
mid_lo = ['shady','dim','grey','faint','weak','dim','shadowy','vague','wispy','feeble','light','swooning','light-headed','lightheaded','fainthearted','timid','faint-hearted','cloudy','muddy','murky','turbid']
mid_hi = ['light','shiny','clear','lustrous','diaphanous','filmy','gauze-like','gossamer','see-through','sheer','transparent','vaporous','vapourous','cobwebby']
extreme_hi = ['blinding','superbright','brilliant','vivid','brilliant','vivid','smart','burnished','lustrous','shining','shiny','undimmed','promising','sunny','sunshiny']

preamble = ['Now it is hella ','Oh, just a bit ','It is quite ','Gosh it is ','Well looky here, it is ','Suddenly: ','Call the police, it is ','After awhile: ','Things have changed; now it\'s more ']

v = vcnl.VCNL4000()

printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5)
printer.begin()
printer.upsideDownOn()
printer.feed(1)
printer.print('i am awake and i am dreaming')
printer.feed(1)
printer.print(str(time.ctime()))
printer.feed(1)
rPast = 0
emission_threshold = 100

def parseLen(text):
    L = []
    # add newlines to cause text to print properly
    # we need this because we're printing upside-down text
    # "call the police, it is faint-hearted" should be printed as
    # "rted" then linebreak then "Call the police, it is faint-hea"
    # which is "rted\nCall the police, it is faint-hea"

    if len(text) > Adafruit_Thermal.maxColumn: # 32 is defined by the printer; max chars per line
Ejemplo n.º 2
0
import subprocess, time, Image, socket
from Adafruit_Thermal import *

printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)

# Print greeting image
# Because the hello/goodbye images are overall fairly light, we can
# get away with using a darker heat time for these, then reset to the
# default afterward.
ht = printer.defaultHeatTime * 2
if(ht > 255): ht = 255

printer.begin(ht) # Set temporary dark heat time
image_file = Image.open('gfx/partlycloudy.gif')
image_100 = image_file.resize((100,100),Image.ANTIALIAS)
image_200 = image_file.resize((200,200),Image.ANTIALIAS)
image_file = image_file.convert('L')
image_100 = image_100.convert('L')
image_200 = image_200.convert('L')
printer.print("Image 50x50")
printer.printImage(image_file, True)
printer.feed(3)
printer.print("Image 100x100")
printer.printImage(image_100, True)
printer.feed(3)
printer.print("Image 200x200")
printer.printImage(image_200, True)
printer.feed(3)
printer.begin() # Reset default heat time

Ejemplo n.º 3
0
            #print("Message Action:", i[3])
            #print('')
            #print("Message #:", i[0])
            print(i[1])
            #print("Message Type:", i[2])
            print(i[2])
            print(i[3])
            print('')
            
            if i[2] == "T":
                #printer.doubleWidthOn()
                #printer.inverseOn()
                printer.printImage(Image.open('40in20out_trade.bmp'), True)
                printer.feed(1)
                printer.inverseOn()
                printer.print ('{:<32}'.format(i[1]))
                #printer.print(i[1])
                printer.inverseOff()
                printer.feed(1)
                printer.boldOn()
                printer.print(i[3])
                printer.boldOff()
                #printer.doubleWidthOff()
                printer.feed(3)

            if i[2] == "2":
                #printer.doubleWidthOn()
                #printer.inverseOn()
                printer.printImage(Image.open('40in20out_2min.bmp'), True)
                printer.feed(1)
                printer.inverseOn()
Ejemplo n.º 4
0
# Enable LED and button (w/pull-up on latter)
GPIO.setup(ledPin, GPIO.OUT)
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# LED on while working
GPIO.output(ledPin, GPIO.HIGH)

# Processor load is heavy at startup; wait a moment to avoid
# stalling during greeting.
time.sleep(30)

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 0))
    printer.print("My IP address is " + s.getsockname()[0])
    printer.feed(3)
except:
    printer.boldOn()
    printer.println("Network is unreachable.")
    printer.boldOff()
    printer.print("Connect display and keyboard\n" "for network troubleshooting.")
    printer.feed(3)
    exit(0)

# Print greeting image
printer.printImage(Image.open("gfx/hello.png"), True)
printer.feed(3)
GPIO.output(ledPin, GPIO.LOW)

# Poll initial button state and time
Ejemplo n.º 5
0
    printer.print(deg)
    printer.print(' high ' + str(hi))
    printer.print(deg)
    printer.println(' ' + cond.replace('\u2013', '-').encode('utf-8'))  # take care of pesky unicode dash


printer = Adafruit_Thermal("/dev/serial0", baudrate=19200, timeout=5)
deg = chr(0xf8)  # Degree symbol on thermal printer

url = "https://api.darksky.net/forecast/" + API_KEY + "/" + LAT + "," + LONG + "?exclude=[alerts,minutely,hourly,flags]&units=ca"
response = urllib.request.urlopen(url)
data = json.loads(response.read())

# Print heading
printer.inverseOn()
printer.print('{:^32}'.format("DarkSky.Net Forecast"))
printer.inverseOff()

# Print current conditions
printer.boldOn()
printer.print('{:^32}'.format('Current conditions:'))
printer.boldOff()

temp = data['currently']['temperature']
cond = data['currently']['summary']
printer.print(temp)
printer.print(deg)
printer.println(' ' + cond)
printer.boldOn()

# Print forecast
Ejemplo n.º 6
0
  None,
  {'Host'            : host,
   'User-Agent'      : agent,
   'Accept-Encoding' : 'gzip',
   'Authorization'   : 'Bearer ' + token})


# Display results. ---------------------------------------------------------

maxId = data['search_metadata']['max_id_str']

for tweet in data['statuses']:

  printer.doubleWidthOn()
  #printer.inverseOn()
  printer.print(' ' + '{:<31}'.format(tweet['user']['screen_name']))
  #print (' ' + '{:<31}'.format(tweet['user']['screen_name']))
  printer.doubleWidthOff()

  printer.inverseOn()
  #printer.print('{:<32}'.format(tweet['created_at']))
  clean_timestamp = datetime.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y')
  offset_hours = -5 #offset in hours for CST/EST timezone
  #account for offset from UTC using timedelta                                
  local_timestamp = clean_timestamp + timedelta(hours=offset_hours)
  #convert to am/pm format for easy reading
  final_timestamp =  datetime.strftime(local_timestamp,'%Y-%m-%d %I:%M:%S %p')  
  final_timestamp =  datetime.strftime(local_timestamp,'%a %b %d %I:%M:%S %p') 
  #print ('{:<32}'.format(tweet['created_at']))
  printer.print ('{:<32}'.format(final_timestamp))
  printer.inverseOff()
Ejemplo n.º 7
0
if 'url' in lastPost['media_content'][0]:
    lastPostImgLink = lastPost['media_content'][0]['url']
    lastPostImgFile = io.BytesIO(
        urllib.request.urlopen(lastPostImgLink).read())
    lastPostImg = Image.open(lastPostImgFile)

    basewidth = 400
    wpercent = (basewidth / float(lastPostImg.size[0]))
    hsize = int((float(lastPostImg.size[1]) * float(wpercent)))
    lastPostImgScaled = lastPostImg.resize((basewidth, hsize), Image.ANTIALIAS)

if postDate > lastPostDate:
    # Print last feed, starting with source
    printer.underlineOn()
    #printer.inverseOn()
    printer.print("" + NewsFeed.feed['title'])
    #printer.inverseOff()
    printer.underlineOff()

    printer.print('\n ' + lastPost.published[0:-6] + '\n' + '\n')

    if lastPostImgScaled != None:
        printer.printImage(lastPostImgScaled, True)

    printer.underlineOn()
    printer.print(lastPost.title + '\n')
    printer.underlineOff()

    lastPostTextContent = lastPost.summary_detail['value']
    TextSectionMarkerOut = lastPostTextContent.find('<br />')
    lastPostText = lastPostTextContent[:TextSectionMarkerOut]
Ejemplo n.º 8
0
    query_url = 'http://dataservice.accuweather.com/forecasts/v1/daily/5day/' + LOCID + '?apikey=' + APIKEY

    #  print(query_url)

    response = (urllib.urlopen(query_url).read())

    # print(response)
    # print('Loading json data from response string')
    data = json.loads(response)

    headline = data['Headline']['Text']

    # Print heading
    printer.boldOn()
    printer.print('{:^32}'.format('5 Day Forecast'))
    printer.boldOff()

    # Print head line
    printer.println('{:^32}'.format(headline))
    printer.println()

    forecast(0)
    forecast(1)
    forecast(2)
    forecast(3)
    forecast(4)
    printer.feed(3)

except:
    # printer.println('--Connection Error--')  # debugging
  # print(type(data['DailyForecasts']))

  # print('Printing type list[0]')
  # print(type(data['DailyForecasts'][0]))
  # print('Printing list[0]:EpochDate')
  epoch =  data['DailyForecasts'][0]['EpochDate']

  # print(epoch)

  # print('converting to weekday')
  weekday = dayOfWeek(epoch)
  # print(weekday)

  # Print heading
  printer.boldOn()
  printer.print('{:^32}'.format('5 Day Forecast'))
  printer.boldOff()

  # Print current conditions
  printer.boldOn()
  printer.print('{:^32}'.format('Current conditions:')) 
  printer.boldOff()
  printer.println('{:^32}'.format(conditions))
  printer.println()
  print('Calling forecast 0')
  forecast(0)
  print('Calling forecast 1')
  forecast(1)
  print('Calling forecast 2')
  forecast(2)
  print('Calling forecast 3')
Ejemplo n.º 10
0
# weather example using nice bitmaps.
# Written by Adafruit Industries.  MIT license.
#
# Required software includes Adafruit_Thermal and PySerial libraries.
# Other libraries used are part of stock Python install.
#
# Resources:
# http://www.adafruit.com/products/597 Mini Thermal Receipt Printer
# http://www.adafruit.com/products/600 Printer starter pack

from __future__ import print_function
from random import choice
from Adafruit_Thermal import *
import urllib, json

printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)

url = "https://niceties.herokuapp.com"
response = urllib.urlopen(url)
data = json.loads(response.read())
recursors = ["Bobby (Robert) DeLanghe"]

# Print nice thing
printer.inverseOn()
printer.print(' ' + choice(recursors) + ' \n')
printer.inverseOff()
printer.print(data)

# Print feed
printer.feed(6)
Ejemplo n.º 11
0
#!/usr/bin/python
from __future__ import print_function
import RPi.GPIO as GPIO
import subprocess, time, Image, socket
from Adafruit_Thermal import *

printer      = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
printer.begin(60)
printer.printImage(Image.open('gfx/hello.png'), True)
printer.print('Hello World blabla blabla blabla')
printer.feed(3)
Ejemplo n.º 12
0
    printer.print(day + ": low " + lo)
    printer.print(deg)
    printer.print(" high " + hi)
    printer.print(deg)
    printer.println(" " + cond)


printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
deg = chr(0xF8)  # Degree symbol on thermal printer

# Fetch forecast data from Yahoo!, parse resulting XML
dom = parseString(urllib.urlopen("http://weather.yahooapis.com/forecastrss?w=" + WOEID).read())

# Print heading
printer.inverseOn()
printer.print("{:^32}".format(dom.getElementsByTagName("description")[0].firstChild.data))
printer.inverseOff()

# Print current conditions
printer.boldOn()
printer.print("{:^32}".format("Current conditions:"))
printer.boldOff()
printer.print("{:^32}".format(dom.getElementsByTagName("pubDate")[0].firstChild.data))
temp = dom.getElementsByTagName("yweather:condition")[0].getAttribute("temp")
cond = dom.getElementsByTagName("yweather:condition")[0].getAttribute("text")
printer.print(temp)
printer.print(deg)
printer.println(" " + cond)
printer.boldOn()

# Print forecast
  None,
  {'Host'            : host,
   'User-Agent'      : agent,
   'Accept-Encoding' : 'gzip',
   'Authorization'   : 'Bearer ' + token})

#print(data)

# Display results. ---------------------------------------------------------

maxId = data['search_metadata']['max_id_str']

for tweet in data['statuses']:

  printer.underlineOn()
  printer.print('{:<31}'.format(tweet['user']['screen_name'])+' auf Twitter unter #NordendOF')
  printer.underlineOff()
  
  printer.feed(1)

  printer.print('{:<32}'.format(tweet['created_at']))
  
  printer.feed(2)

  if 'extended_entities' in tweet:
    getpic = tweet['extended_entities']['media'][0]['media_url']
    pic = Image.open(urllib.request.urlopen(getpic))
    basewidth = 400
    wpercent = (basewidth / float(pic.size[0]))
    hsize = int((float(pic.size[1]) * float(wpercent)))
    img = pic.resize((basewidth, hsize), Image.ANTIALIAS)
Ejemplo n.º 14
0
except:
  print(lastId)
  exit(0)

# Display results. ---------------------------------------------------------

maxId = data['search_metadata']['max_id_str']

for tweet in data['statuses']:
  decoded_text = unidecode(HTMLParser.HTMLParser().unescape(tweet['text']))

  if (ignore_replies and decoded_text[0] == '@'):
      continue

  printer.inverseOn()
  printer.print(' ' + '{:<31}'.format(tweet['user']['screen_name']))
  printer.inverseOff()

  printer.underlineOn()
  printer.print('{:<32}'.format(tweet['created_at']))
  printer.underlineOff()

  # max_id_str is not always present, so check tweet IDs as fallback
  id = tweet['id_str']
  if(id > maxId): maxId = id # String compare is OK for this

  # Remove HTML escape sequences
  # and remap Unicode values to nearest ASCII equivalents
  printer.print(decoded_text)

  printer.feed(3)
Ejemplo n.º 15
0
    'blinding', 'superbright', 'brilliant', 'vivid', 'brilliant', 'vivid',
    'smart', 'burnished', 'lustrous', 'shining', 'shiny', 'undimmed',
    'promising', 'sunny', 'sunshiny'
]

preamble = [
    'Now it is hella ', 'Oh, just a bit ', 'It is quite ', 'Gosh it is ',
    'Well looky here, it is ', 'Suddenly: ', 'Call the police, it is ',
    'After awhile: ', 'Things have changed; now it\'s more '
]

printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5)
printer.begin()
printer.upsideDownOn()
printer.feed(3)
printer.print("o hai")
printer.feed(1)
rPast = 0
emission_threshold = 0.05


def parseLen(text):
    L = []
    # add newlines to cause text to print properly
    # we need this because we're printing upside-down text
    # "call the police, it is faint-hearted" should be printed as
    # "rted" then linebreak then "Call the police, it is faint-hea"
    # which is "rted\nCall the police, it is faint-hea"

    if len(
            text
Ejemplo n.º 16
0
#
# Prints a series of black bars with increasing "heat time" settings.
# Because printed sections have different "grip" characteristics than
# blank paper, as this progresses the paper will usually at some point
# jam -- either uniformly, making a short bar, or at one side or the
# other, making a wedge shape.  In some cases, the Pi may reset for
# lack of power.
#
# Whatever the outcome, take the last number printed BEFORE any
# distorted bar and enter in in Adafruit_Thermal.py as defaultHeatTime
# (around line 53).
#
# You may need to pull on the paper as it reaches the jamming point,
# and/or just abort the program, press the feed button and take the
# last good number.

from __future__ import print_function
from Adafruit_Thermal import *

printer = Adafruit_Thermal("/dev/tty.NoZAP-PL2303-00005014", 19200, timeout=5)

for i in range(0, 256, 15):
    printer.begin(i)
    printer.println(i)  # Print heat time
    printer.inverseOn()
    printer.print("{:^32}".format(""))  # Print 32 spaces (inverted)
    printer.inverseOff()

printer.begin()  # Reset heat time to default
printer.feed(4)
Ejemplo n.º 17
0
        toRet = clamp(toRet, outMin, outMax)
        return toRet

def clamp(val, tmin, tmax):
    if val > tmax:
        val = tmax
    if val < tmin:
        val = tmin
    return val


uart.setup("UART2")
adc.setup()
atexit.register(exit_handler)
printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5)
printer.begin()
printer.upsideDownOn()
printer.feed(3)
printer.print(parse('i am awake and I am APPLE (light)'))
printer.feed(1)
rPast = 0
rMax = 0 # all-time max sensor reading
rMin = 100000 # all-time min sensor reading
WINDOW_SIZE = 30 # size of moving-window avg
noop = 0 # number of intervals passed without a trigger
noop_threshold = 480
emission_threshold = 0.1 # changed this for vcnl4000, used to be 0.7

while True:
    checkSensor()
    time.sleep(0.5)
Ejemplo n.º 18
0
 ["What is a ghost's favorite mode of transportation", 'A scare-plane.'],
 ["Why couldn't the vampire's wife get to sleep",
  "Because of her husband's coffin."],
 ['Why was the little ghost stupid', 'Because he climbed over walls.'],
 ['Why do ghosts like tall buildings',
  'Because they have a lot of scare-cases.'],
 ['What do ghosts add to their morning cereal', 'Boo-berries.'],
 ['What does a vampire never order at a restaurant', 'A stake sandwich.'],
 ['What does a ghost eat for lunch', 'A boo-logna sandwich.'],
 ['Why are vampire jokes bad', 'Because they are a pain in the neck.'],
 ['Where did the vampire open his savings account', 'At a blood bank.'],
 ['What do you get when you cross a ghost with an owl',
  "Something that scares people and doesn't give a hoot."],
 ['What do short-sighted ghosts wear', 'Spook-tacles.'],
 ['What do you say to a skeleton before he eats', 'Bone appetit!'],
 ['Why do witches fly on brooms', 'Because vacuum cleaners are too heavy.'],
 ["Why don't witches ride their brooms when they're angry",
  "They're afraid of flying off the handle!"]]

joke = choice(jokes)

printer.inverseOn()
printer.print('{}?\n'.format(joke[0]))
printer.inverseOff()

printer.underlineOn()
printer.print('{}\n'.format(joke[1]))
printer.underlineOff()

printer.feed(4)
    printer.inverseOff()

    printer.underlineOn()
    #printer.print('{:<32}'.format(tweet['created_at']))
    printer.underlineOff()

    # max_id_str is not always present, so check tweet IDs as fallback
    id = tweet['id_str']
    if (id > maxId): maxId = id  # String compare is OK for this

    # Remove HTML escape sequences
    # and remap Unicode values to nearest ASCII equivalents
    theTweet = unidecode(HTMLParser.HTMLParser().unescape(tweet['text']))
    thingIndex = theTweet.find('|')
    theTweet = theTweet[:thingIndex]
    #printer.feed(1)
    printer.setSize('L')
    printer.justify('C')
    printer.print('\n')
    printer.print(str(theTweet))
    printer.print('\n')
    printer.setSize('M')
    printer.print('Thank You!')
    printer.print('\n\n')
    printer.setSize('S')
    printer.justify('L')
    printer.feed(3)

sys.stderr.write(maxId)
print(maxId)  # Piped back to calling process
Ejemplo n.º 20
0
	printer.print(' / Max. ' + hi)
	printer.print(deg)
	printer.feed(1)
	printer.println(conditions[int(cond)])

printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
deg     = chr(0xf8) # Degree symbol on thermal printer

# Fetch forecast data from Yahoo!, parse resulting XML
dom = parseString(urllib.urlopen(
        'http://weather.yahooapis.com/forecastrss?u=' + tempUnit +
        '&w=' + WOEID).read())

# Print heading
printer.inverseOn()
printer.print('{:^32}'.format(
  dom.getElementsByTagName('description')[0].firstChild.data))
printer.feed(1)
printer.inverseOff()

# Print current conditions
printer.feed(1)
printer.boldOn()
printer.print('{:^32}'.format('Weersomstandigheden:'))
printer.boldOff()
printer.print(dom.getElementsByTagName('pubDate')[0].firstChild.data)
temp = dom.getElementsByTagName('yweather:condition')[0].getAttribute('temp')
cond = dom.getElementsByTagName('yweather:condition')[0].getAttribute('code')
printer.feed(1)
printer.boldOn()
printer.print(temp)
printer.print(deg)
        #fake Agent to avoid 403 - forbidden message from python agent
        req = urllib.request.Request(lastPostImgLink,
                                     headers={'User-Agent': 'Mozilla/5.0'})
        lastPostImgFile = io.BytesIO(urllib.request.urlopen(req).read())
        lastPostImg = Image.open(lastPostImgFile)

        basewidth = 300
        wpercent = (basewidth / float(lastPostImg.size[0]))
        hsize = int((float(lastPostImg.size[1]) * float(wpercent)))
        lastPostImgScaled = lastPostImg.resize((basewidth, hsize),
                                               Image.ANTIALIAS)

    # Print last feed, starting with source
    printer.underlineOn()
    #printer.inverseOn()
    printer.print("" + NewsFeed.feed['title'])
    #printer.inverseOff()
    printer.underlineOff()

    printer.print(lastPost.published[0:-6] + '\n' + '\n')

    if lastPostImgScaled != None:
        printer.printImage(lastPostImgScaled, True)

    printer.underlineOn()
    printer.print(lastPost.title + '\n')
    printer.underlineOff()
    printer.print(lastPost.summary_detail['value'] + '\n')

    printer.print('\nDein Kommentar:\n' +
                  '\n................................' +
Ejemplo n.º 22
0
    printer.print(day + ': low ' + str(lo) )
    printer.print(deg)
    printer.print(' high ' + str(hi))
    printer.print(deg)
    printer.println(' ' + cond.replace(u'\u2013', '-').encode('utf-8')) # take care of pesky unicode dash

printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
deg     = chr(0xf8) # Degree symbol on thermal printer

url = "https://api.darksky.net/forecast/"+API_KEY+"/"+LAT+","+LONG+"?exclude=[alerts,minutely,hourly,flags]&units=us"
response = urllib.urlopen(url)
data = json.loads(response.read())

# Print heading
printer.inverseOn()
printer.print('{:^32}'.format("DarkSky.Net Forecast"))
printer.inverseOff()

# Print current conditions
printer.boldOn()
printer.print('{:^32}'.format('Current conditions:'))
printer.boldOff()


temp = data['currently']['temperature']
cond = data['currently']['summary']
printer.print(temp)
printer.print(deg)
printer.println(' ' + cond)
printer.boldOn()
Ejemplo n.º 23
0
  'GET',
  (searchUrl + 'count=3&since_id=%s&q=%s' %
   (lastId, urllib.quote(queryString))),
  None,
  {'Host'            : host,
   'User-Agent'      : agent,
   'Accept-Encoding' : 'gzip',
   'Authorization'   : 'Bearer ' + token})


# Display results. ---------------------------------------------------------

for tweet in data['statuses']:

  printer.inverseOn()
  printer.print(' ' + '{:<31}'.format(tweet['user']['screen_name']))
  printer.inverseOff()

  printer.underlineOn()
  printer.print('{:<32}'.format(tweet['created_at']))
  printer.underlineOff()

  # Remove HTML escape sequences
  # and remap Unicode values to nearest ASCII equivalents
  # Use textwrap module to wrap neatly at 32 characters
  tweettext=textwrap.wrap(unidecode(
    HTMLParser.HTMLParser().unescape(tweet['text'])),32)
  for line in tweettext:
    printer.print(line + "\n")
  printer.feed(3)
Ejemplo n.º 24
0
                  float(float(val - inMin) / float(inMax - inMin)))
    return clamp(toRet, outMin, outMax)


def clamp(val, tmin, tmax):
    if val > tmax:
        val = tmax
    if val < tmin:
        val = tmin
    return val


uart.setup("UART2")
printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5)
printer.begin()
printer.upsideDownOn()
printer.feed(3)
printer.print(parse('i am awake and I am MUG (thermal)'))
printer.feed(1)
rPast = 0
rMax = 0  # all-time max sensor reading
rMin = 0  # all-time min sensor reading
WINDOW_SIZE = 30  # size of moving-window avg
noop = 0  # number of intervals passed without a trigger
noop_threshold = 480
emission_threshold = 0.7

while True:
    checkSensor()
    time.sleep(0.5)
Ejemplo n.º 25
0
#
# Prints a series of black bars with increasing "heat time" settings.
# Because printed sections have different "grip" characteristics than
# blank paper, as this progresses the paper will usually at some point
# jam -- either uniformly, making a short bar, or at one side or the
# other, making a wedge shape.  In some cases, the Pi may reset for
# lack of power.
#
# Whatever the outcome, take the last number printed BEFORE any
# distorted bar and enter in in Adafruit_Thermal.py as defaultHeatTime
# (around line 53).
#
# You may need to pull on the paper as it reaches the jamming point,
# and/or just abort the program, press the feed button and take the
# last good number.

from __future__ import print_function
from Adafruit_Thermal import *

printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5)

for i in range(0, 256, 15):
    printer.begin(i)
    printer.println(i)  # Print heat time
    printer.inverseOn()
    printer.print('{:^32}'.format(''))  # Print 32 spaces (inverted)
    printer.inverseOff()

printer.begin()  # Reset heat time to default
printer.feed(4)
Ejemplo n.º 26
0
GPIO.setup(buttonPin2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(buttonPin4, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(ledPin1, GPIO.OUT)
GPIO.setup(ledPin4, GPIO.OUT)

#10 seconde avant le debut des actions

#on allume la led 3sec
GPIO.output(ledPin1, GPIO.HIGH)
GPIO.output(ledPin4, GPIO.HIGH)
time.sleep(3)

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 0))
    printer.print('Imprimante connectee a internet')
    printer.feed(3)
except:
    printer.boldOn()
    printer.println('Connexion a internet echouee')
    printer.boldOff()
    printer.feed(3)
    exit(0)

query = "efrei"


def tap2():

    GPIO.output(ledPin4, GPIO.LOW)
    print("vous avez appuyé sur le bouton\n")
Ejemplo n.º 27
0
# Enable LED and button (w/pull-up on latter)
GPIO.setup(ledPin, GPIO.OUT)
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# LED on while working
GPIO.output(ledPin, GPIO.HIGH)

# Processor load is heavy at startup; wait a moment to avoid
# stalling during greeting.
time.sleep(30)

# Show IP address (if network is available)
try:
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	s.connect(('8.8.8.8', 0))
	printer.print('My IP address is ' + s.getsockname()[0])
	printer.feed(3)
except:
	printer.boldOn()
	printer.println('Network is unreachable.')
	printer.boldOff()
	printer.print('Connect display and keyboard\n'
	  'for network troubleshooting.')
	printer.feed(3)
	exit(0)

# Print greeting image
printer.printImage(Image.open('gfx/hello.png'), True)
printer.feed(3)
GPIO.output(ledPin, GPIO.LOW)
Ejemplo n.º 28
0
GPIO.output(ledPin, GPIO.HIGH)

# Processor load is heavy at startup; wait a moment to avoid
# stalling during greeting.
time.sleep(30)

# Show IP address (if network is available)
try:
    setIP()
    printIP()
except:
    printer.feed(1)
    printer.boldOn()
    printer.println('Network is unreachable.')
    printer.boldOff()
    printer.print('Connect display and keyboard\n'
                  'for network troubleshooting.')
    printer.feed(3)
    exit(0)

# Print greeting image
printer.printImage(Image.open('gfx/hello.png'), True)
printer.feed(3)
GPIO.output(ledPin, GPIO.LOW)

# Poll initial button state and time
prevButtonState = GPIO.input(buttonPin)
prevTime = time.time()
tapEnable = False
holdEnable = False

# Main loop
Ejemplo n.º 29
0
time.sleep(30)

# Show IP address (if network is available)
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 0))
    printer.feed(1)
except:
    printer.boldOn()
    printer.println('Network is unreachable.')
    printer.boldOff()
    printer.feed(3)
    exit(0)

# Print greeting image
printer.print('"PinnwandConnection" ist ein \nProjekt von studio-johey.de')
printer.feed(1)
printer.printImage(Image.open('JoHey_Black_ThermoPrint.jpg'), True)
printer.feed(3)

# Main loop
while(True):
  # Poll current time
    t = time.time()

  # Once per day (currently set for 6:30am local time, or when script
  # is first run, if after 6:30am), run forecast and sudoku scripts.
##  l = time.localtime()
##  if (60 * l.tm_hour + l.tm_min) > (60 * 8 + 00):
##    if dailyFlag == False:
##      daily()
Ejemplo n.º 30
0
def mapVals(val, inMin, inMax, outMin, outMax):
        toRet = float(outMin + (float(outMax - outMin) * (float(val - inMin) / float(inMax - inMin))))
        # return clamp(toRet, outMin, outMax)
        return toRet

def clamp(val, tmin, tmax):
    if val > tmax:
        val = tmax
    if val < tmin:
        val = tmin
    return val


uart.setup("UART2")
printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5)
printer.begin()
printer.upsideDownOn()
printer.feed(3)
printer.print(parse('i am awake and I am BLOCKS (presence)'))
printer.feed(1)
rPast = 0
rMax = 0 # all-time max sensor reading
rMin = 100000 # all-time min sensor reading
WINDOW_SIZE = 30 # size of moving-window avg
noop = 0 # number of intervals passed without a trigger
noop_threshold = 480
emission_threshold = 5 # changed this for vcnl4000, used to be 0.7

while True:
    checkSensor()
    time.sleep(0.5)
Ejemplo n.º 31
0
data = issueRequestAndDecodeResponse(
    'GET', (searchUrl + 'count=3&since_id=%s&q=%s' %
            (lastId, urllib.quote(queryString))), None, {
                'Host': host,
                'User-Agent': agent,
                'Accept-Encoding': 'gzip',
                'Authorization': 'Bearer ' + token
            })

# Display results. ---------------------------------------------------------

for tweet in data['statuses']:

    printer.inverseOn()
    printer.print(' ' + '{:<31}'.format(tweet['user']['screen_name']))
    printer.inverseOff()

    printer.underlineOn()
    printer.print('{:<32}'.format(tweet['created_at']))
    printer.underlineOff()

    # Remove HTML escape sequences
    # and remap Unicode values to nearest ASCII equivalents
    # Use textwrap module to wrap neatly at 32 characters
    tweettext = textwrap.wrap(
        unidecode(HTMLParser.HTMLParser().unescape(tweet['text'])), 32)
    for line in tweettext:
        printer.print(line + "\n")
    printer.feed(3)
Ejemplo n.º 32
0
def main():
    printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
    response = requests.models.Response

    if len(sys.argv) > 1:
        try:
            # Need to mimic browser
            header = {
                'user-agent':
                'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
            }
            response = requests.get(sys.argv[1], headers=header)
        except:
            print("Are you sure you got the URL correct?")
    else:
        print("How can I do my job if I have no URL?")

    # Some dirty decoding
    dec_response = response.content.decode('utf-8')
    dec_response = dec_response.replace(u'\xbc', '1/4')
    dec_response = dec_response.replace(u'\xbd', '1/2')
    dec_response = dec_response.replace(u'\xbc', '3/4')
    dec_response = dec_response.replace(u'\u2013', '-')
    dec_response = dec_response.replace(u'\xa0', ' ')

    soup = BeautifulSoup(dec_response, 'html.parser')

    printer.boldOn()
    printer.setSize('M')
    title = soup.find("h1", attrs={
        "class": "recipe-header__title"
    }).text.strip()
    wp(title + "\n\n")

    printer.boldOff()
    printer.setSize('S')
    c_times_container = soup.find("div",
                                  attrs={"class": "recipe-details__text"})
    c_times = c_times_container.find_all("span")
    wp("PREP: " + c_times[1].text + "\n")
    wp("COOK: " + c_times[3].text + "\n\n")

    printer.boldOn()
    printer.print("Ingredients:\n")
    printer.boldOff()

    ingredient_list = soup.find("ul",
                                attrs={"class": "ingredients-list__group"})
    for ingredient in ingredient_list.contents:
        wp("- " + ingredient["content"].encode('ascii') + "\n")

    printer.boldOn()
    printer.print("\nMethod:\n")
    printer.boldOff()

    method_list = soup.find("ol", attrs={"class": "method__list"})
    counter = 1
    for instruction in method_list:
        wp(
            str(counter) + ". " + instruction.text.encode('ascii', 'replace') +
            "\n")
        counter += 1

    printer.feed(3)
Ejemplo n.º 33
0
            printer.feed(1)
            if activegame == 1:
                #It's an active game so lets print that results. Then we don't need to check the gamecode.
                #Lets check the active Players
                ocurs = db.cursor()
                sql = "SELECT * FROM activeplayers"
                atotrow = ocurs.execute(sql)
                results = ocurs.fetchall()
                atotrow = ocurs.rowcount
                #We need now to loop thru the Players to print results.
                for row in results:
                    playid = row[0]
                    playname = row[1]
                    gameid = row[2]
                    printer.setSize('S')
                    printer.print("Players: ")
                    printer.println(playname)
                    #Get some info from the game
                    gocurs = db.cursor()
                    sql = "SELECT * FROM games WHERE id = %s"
                    val = (gameid, )
                    gocurs.execute(sql, val)
                    goresult = gocurs.fetchall()
                    for gorow in goresult:
                        gamename = gorow[1]
                        quickroundtotal = gorow[2]

                    #Now lets get game info
                    gcurs = db.cursor()
                    sql1 = "SELECT * FROM activequick WHERE gplayer =%s"
                    val = (playid, )
Ejemplo n.º 34
0
    # slowPrint(parseLen(random.choice(preamble)+random.choice(extreme_hi)))
    # printer.feed(1)

def exit_handler():
    pass
    # print 'exiting'
    # adc.cleanup()
    # uart.cleanup() # not yet supported?

def mapVals(val, inMin, inMax, outMin, outMax):
        toRet = outMin + (outMax - outMin) * ((val - inMin) / (inMax - inMin))
        return toRet

uart.setup("UART2")
printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5)
printer.begin()
printer.upsideDownOn()
printer.feed(3)
printer.print('i am awake and I have a TMP102')
printer.feed(1)
rPast = 0
rMax = 0 # all-time max sensor reading
rMin = 0 # all-time min sensor reading
WINDOW_SIZE = 30 # size of moving-window avg
noop = 0 # number of intervals passed without a trigger
noop_threshold = 480
emission_threshold = 0.7

while True:
    checkSensor()
    time.sleep(0.5)
Ejemplo n.º 35
0
class Printer(object):
    """This class represents the printer"""

    def __init__(self, device, baud_rate, timeout):
        """Printer initialization
        
        :param device: Device path
        :type device: str
        :param baud: Baud rate
        :type baud: int
        :param timeout: Timeout in seconds
        :type timeout: int
        """
        self.print_size = 384, 384  # max_width=384

        self.device = Adafruit_Thermal(device, baud_rate, timeout=timeout)

    def _calibrate(self):
        for i in range(0, 256, 15):
            self.device.begin(i)
            self.device.println(i)  # Print heat time
            self.device.inverseOn()
            self.device.print("{:^32}".format(""))  # Print 32 spaces (inverted)
            self.device.inverseOff()

        self.device.begin()  # Reset heat time to default
        self.device.feed(4)

    def print_image(self, image_file_path, event):
        """Print Image

        :param image_file_path: Image file path
        :type image_file_path: str
        """
        # print logo
        self.device.printImage(Image.open(event["logo"]), True)

        self.device.justify("C")

        self.device.doubleHeightOn()
        self.device.println(event["title"])

        self.device.doubleHeightOff()
        self.device.println(datetime.now().strftime("%d-%m-%Y %H:%M:%S"))  # time

        self.device.feed(1)

        # print picture
        image_code = os.path.splitext(os.path.basename(image_file_path))[0]
        image_for_print_path = "{}.print".format(image_file_path)
        image_for_print = Image.open(image_file_path)  # create proxy image for print
        image_for_print = image_for_print.transpose(Image.ROTATE_180)  # rotate image
        w, h = image_for_print.size
        image_for_print.crop((int((w - h) / 2), 0, int((w - h) / 2), 0))
        image_for_print.thumbnail(self.print_size, Image.ANTIALIAS)  # resize
        image_for_print.save(image_for_print_path, "JPEG")  # save
        self.device.printImage(Image.open(image_for_print_path), True)
        self.device.feed(1)

        # print text
        self.device.println(event["place"])
        self.device.feed(1)

        # line
        self.device.println("------------------------------")

        self.device.feed(1)
        self.device.boldOn()
        self.device.println("partagez votre")
        self.device.println("photo avec le code")
        self.device.boldOff()
        self.device.doubleHeightOn()
        self.device.doubleWidthOn()
        self.device.println(image_code)
        self.device.doubleWidthOff()
        self.device.doubleHeightOff()
        self.device.boldOn()
        self.device.println("sur")
        self.device.boldOff()
        self.device.println("shootomatic.net")
        self.device.feed(1)

        # line
        self.device.println("------------------------------")

        # space to detach
        self.device.feed(3)

        # delete proxy image used for print
        os.remove(image_for_print_path)
Ejemplo n.º 36
0
    # authenication block, see http://www.rememberthemilk.com/services/api/authentication.rtm
    # check for valid token
    if not api.token_valid():
        # use desktop-type authentication
        url, frob = api.authenticate_desktop()
        # open webbrowser, wait until user authorized application
        print ("URL you need to open: %s" % url)
        webbrowser.open(url)
        raw_input("Continue?")
        # get the token for the frob
        api.retrieve_token(frob)
        # print out new token, should be used to initialize the Rtm object next time
        print ("token: %s" % api.token)
        f1=open('./rtm_const', 'w+')
        f1.write("token: %s\n" % api.token)
        print ("You're going to need to remove the duplicate token line\n")
        f1.close

    printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)

    # get all open tasks, see http://www.rememberthemilk.com/services/api/methods/rtm.tasks.getList.rtm
    result = api.rtm.tasks.getList(filter="due:today")

    box     = chr(0xaf) # Degree symbol on thermal printer
    printer.println("------------------------------")
    for tasklist in result.tasks:
        for taskseries in tasklist:
            printer.print("{} {}\n".format(box, taskseries.name))

    printer.println("------------------------------")
Ejemplo n.º 37
0
	printer.print(day + ': low ' + lo )
	printer.print(deg)
	printer.print(' high ' + hi)
	printer.print(deg)
	printer.println(' ' + cond)

printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
deg     = chr(0xf8) # Degree symbol on thermal printer

# Fetch forecast data from Yahoo!, parse resulting XML
dom = parseString(urllib.urlopen(
        'http://weather.yahooapis.com/forecastrss?u=c&w=' + WOEID).read())

# Print heading
printer.inverseOn()
printer.print('{:^32}'.format(
  dom.getElementsByTagName('description')[0].firstChild.data))
printer.inverseOff()

# Print current conditions
printer.boldOn()
printer.print('{:^32}'.format('Current conditions:'))
printer.boldOff()
printer.print('{:^32}'.format(
  dom.getElementsByTagName('pubDate')[0].firstChild.data))
temp = dom.getElementsByTagName('yweather:condition')[0].getAttribute('temp')
cond = dom.getElementsByTagName('yweather:condition')[0].getAttribute('text')
printer.print(temp)
printer.print(deg)
printer.println(' ' + cond)
printer.boldOn()
Ejemplo n.º 38
0
try:
    subprocess.check_call(["sudo", "checkWifi.sh"])
    printer.println('Network OK')

except:
    # Show network error information

    printer.boldOn()
    printer.println('Network is unreachable')
    printer.underlineOn()
    printer.println('Resetting Connection')
    printer.underlineOff()
    printer.boldOff()

    # Reset wifi
    subprocess.call(["sudo", "resetWifi.sh"])
    time.sleep(30)

    # Test Network and show result
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 0))
        printer.feed(1)
        printer.print('My IP address is ' + s.getsockname()[0])
    except:
        printer.println('Network is still unreachable.')

printer.feed(3)

GPIO.output(ledPin, GPIO.LOW)
Ejemplo n.º 39
0
GPIO.setup(ledPin, GPIO.OUT)
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# LED on while working
GPIO.output(ledPin, GPIO.HIGH)

# Processor load is heavy at startup; wait a moment to avoid
# stalling during greeting.
time.sleep(5)


if logonFlag == False:
  # hit the url
  url = "http://www.40in20out.com/boxlogon.asp?action=LOGON&boxid=" + cBoxID
  queryString = urllib.urlopen(url).read()
  printer.print(queryString)
  printer.feed(1)
  logonFlag = True


# Show IP address (if network is available)
try:
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	s.connect(('8.8.8.8', 0))
	printer.print('IP address: ' + s.getsockname()[0])
        ip = s.getsockname()[0]
	printer.feed(1)
except:
	printer.boldOn()
	printer.println('Network is unreachable.')
	printer.boldOff()
Ejemplo n.º 40
0
# Enable LED and button (w/pull-up on latter)
GPIO.setup(ledPin, GPIO.OUT)
for buttonPin in buttonPins:
    GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# LED on for now
GPIO.output(ledPin, GPIO.HIGH)

# Processor load is heavy at startup; wait a moment to avoid
# stalling during greeting.
time.sleep(30)

printer.feed(2)
printer.boldOn()
printer.print("Grace & Dad's Calendar Printer")
printer.boldOff()
printer.feed(1)

# Show IP address (if network is available)
try:
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	s.connect(('8.8.8.8', 0))
	printer.print('My IP address is ' + s.getsockname()[0])
	printer.feed(3)
except:
	printer.boldOn()
	printer.println('Network is unreachable.')
	printer.boldOff()
	printer.print('Connect display and keyboard\n'
	  'for network troubleshooting.')
Ejemplo n.º 41
0
    'GET', (searchUrl + 'count=3&since_id=%s&q=%s' %
            (lastId, urllib.quote(queryString))), None, {
                'Host': host,
                'User-Agent': agent,
                'Accept-Encoding': 'gzip',
                'Authorization': 'Bearer ' + token
            })

# Display results. ---------------------------------------------------------

maxId = data['search_metadata']['max_id_str']

for tweet in data['statuses']:

    printer.inverseOn()
    printer.print(' ' + '{:<31}'.format(tweet['user']['screen_name']))
    printer.inverseOff()

    printer.underlineOn()
    printer.print('{:<32}'.format(tweet['created_at']))
    printer.underlineOff()

    # max_id_str is not always present, so check tweet IDs as fallback
    id = tweet['id_str']
    if (id > maxId): maxId = id  # String compare is OK for this

    # Remove HTML escape sequences
    # and remap Unicode values to nearest ASCII equivalents
    printer.print(unidecode(HTMLParser.HTMLParser().unescape(tweet['text'])))

    printer.feed(3)
import random
import atexit

sensor_pin = 'P9_40'
extreme_lo = ['dark','inky','shadowed','midnight''black','sinister','dour','glowering','glum','moody','morose','saturnine','sour','sullen','benighted','obscure','blue','dingy','disconsolate','dismal','gloomy','grim','sorry','drab','drear','dreary','colored','coloured','dark-skinned','non-white','depressing','dispiriting']
mid_lo = ['shady','dim','grey','faint','weak','dim','shadowy','vague','wispy','feeble','light','swooning','light-headed','lightheaded','fainthearted','timid','faint-hearted','cloudy','muddy','murky','turbid']
mid_hi = ['light','shiny','clear','lustrous','diaphanous','filmy','gauze-like','gossamer','see-through','sheer','transparent','vaporous','vapourous','cobwebby']
extreme_hi = ['blinding','superbright','brilliant','vivid','brilliant','vivid','smart','burnished','lustrous','shining','shiny','undimmed','promising','sunny','sunshiny']

preamble = ['Now it is hella ','Oh, just a bit ','It is quite ','Gosh it is ','Well looky here, it is ','Suddenly: ','Call the police, it is ','After awhile: ','Things have changed; now it\'s more ']

printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5)
printer.begin()
printer.upsideDownOn()
printer.feed(3)
printer.print("o hai")
printer.feed(1)
rPast = 0
emission_threshold = 0.05

def parseLen(text):
	L = []
	# add newlines to cause text to print properly
	# we need this because we're printing upside-down text
	# "call the police, it is faint-hearted" should be printed as
	# "rted" then linebreak then "Call the police, it is faint-hea"
	# which is "rted\nCall the police, it is faint-hea"

	if len(text) > Adafruit_Thermal.maxColumn: # 32 is defined by the printer; max chars per line
		r = len(text)%32
		L.append(text[-r:]+'\n')
Ejemplo n.º 43
0
#!/usr/bin/python

from __future__ import print_function
import base64, json, sys, urllib, zlib
from Adafruit_Thermal import *

import urllib.request
import lxml as lh

url = "http://readpoopfiction.com/story.php?length=1"
page = urllib.request.urlopen(url)
doc = str(page.read())
index = doc.find("<p class=\"author\">")
doc = doc[index:-1]
index = doc.find("<p>")
doc = doc[index + 3:-1]
end = doc.find("<p class=\"more\">")
result = doc[:end].replace("</p>", "").replace("\\t", "").replace(
    "\\n",
    "").replace("\\r", "").replace("<p>", "\n").replace("&nbsp;", " ").replace(
        "&ldquo;", "\"").replace("&rdquo;", "\"").split("<br />")

printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
for x in result:
    printer.print(x)
    printer.println(' ')

printer.feed(3)
    #get and scale post image for printer roll
    lastPostImgScaled = None

    lastPostImgLink = lastPost['media_content'][0]['url']
    lastPostImgFile = io.BytesIO(
        urllib.request.urlopen(lastPostImgLink).read())
    lastPostImg = Image.open(lastPostImgFile)

    basewidth = 400
    wpercent = (basewidth / float(lastPostImg.size[0]))
    hsize = int((float(lastPostImg.size[1]) * float(wpercent)))
    lastPostImgScaled = lastPostImg.resize((basewidth, hsize), Image.ANTIALIAS)

    # Print last feed, starting with source
    printer.underlineOn()
    printer.print("Letzter Post von \n" + NewsFeed.feed['title'])
    printer.underlineOff()

    printer.print('\n ' + lastPost.published[0:-5] + '\n' + '\n')

    if lastPostImgScaled != None:
        printer.printImage(lastPostImgScaled, True)

#    lastPostTextContent = lastPost.summary_detail['value']
#    TextSectionMarkerIn = lastPostTextContent.find('<br/>')
#    #TextSectionMarkerOut = lastPostTextContent.find('<br />')
#    lastPostText = lastPostTextContent[TextSectionMarkerIn+5:-1]
#    printer.print(lastPostText)

    lastPostTextContent = lastPost.summary_detail['value']
    TextSectionMarkerIn = lastPostTextContent.find('<br/>')
Ejemplo n.º 45
0
# Enable LED and button (w/pull-up on latter)
GPIO.setup(ledPin, GPIO.OUT)
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# LED on while working
GPIO.output(ledPin, GPIO.HIGH)

# Processor load is heavy at startup; wait a moment to avoid
# stalling during greeting.
time.sleep(30)

# Show IP address (if network is available)
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 0))
    printer.print('Welcome to the Tatadada Table! \n My IP address is ' + s.getsockname()[0])
    printer.feed(3)
except:
    printer.boldOn()
    printer.println('Network is unreachable.')
    printer.boldOff()
    printer.print('Connect display and keyboard\n'
                  'for network troubleshooting.')
    printer.feed(3)
    exit(0)

# Print greeting image
# printer.printImage(Image.open('gfx/welcome.png'), True)
# printer.feed(3)

printer.printImage(Image.open('gfx/logo-tatadada.png'), True)
Ejemplo n.º 46
0
GPIO.output(ledPin4, GPIO.LOW)

prevButtonState1 = GPIO.input(buttonPin1)
prevTime        = time.time()

tapEnable1       = False
holdEnable1      = False

tapTime      = 0.1
holdTime     = 2

GPIO.output(ledPin1, GPIO.HIGH)

time.sleep(5)
printer.feed(1)
printer.print("Imprimante desactivee appuyez sur le bouton 3 pour continuer\n")
printer.feed(2)



while(True):

    buttonState1 = GPIO.input(buttonPin1)
    t1 = time.time()


    if buttonState1 != prevButtonState1:
        prevButtonState1 = buttonState1   # Si l'etat a changé, nouveau etat/temps
        prevTime        = t1
    else:                             # si il ne change pas
        if (t1 - prevTime) >= holdTime:  # resté appuyé ?
Ejemplo n.º 47
0
def main():
    p = Adafruit_Thermal()
    p.setDefault()
    p.setSize('L')
    p.println('Calendar')

    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)

        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    now = datetime.utcnow().isoformat() + 'Z'
    timeMax = (datetime.utcnow() +
               timedelta(days=config.calendar_days)).isoformat() + 'Z'
    event_results = service.events().list(calendarId='primary',
                                          timeMin=now,
                                          timeMax=timeMax,
                                          singleEvents=True,
                                          orderBy='startTime').execute()
    events = event_results.get('items', [])

    p.setSize('M')
    if not events:
        p.println("Nothing to do... chill out!")

    for event in events:
        # print(event)
        start_d_in = event['start'].get('date')
        start_dt_in = event['start'].get('dateTime')

        start_t_out = None
        if start_dt_in is not None:
            start_dt = dateutil.parser.parse(start_dt_in)
            start_d_out = start_dt.strftime(config.date_format)
            start_t_out = start_dt.strftime(config.time_format)
        else:
            start_d_out = dateutil.parser.parse(start_d_in).strftime(
                config.date_format)

        p.boldOn()
        p.underlineOn()
        p.justify('L')
        if start_t_out is not None:
            p.print(start_t_out)
            p.print(' ')

        p.println(start_d_out)
        p.boldOff()
        p.underlineOff()

        p.justify('R')
        p.println(event['summary'])

    p.setDefault()
    p.sleep()
#
# Prints a series of black bars with increasing "heat time" settings.
# Because printed sections have different "grip" characteristics than
# blank paper, as this progresses the paper will usually at some point
# jam -- either uniformly, making a short bar, or at one side or the
# other, making a wedge shape.  In some cases, the Pi may reset for
# lack of power.
#
# Whatever the outcome, take the last number printed BEFORE any
# distorted bar and enter in in Adafruit_Thermal.py as defaultHeatTime
# (around line 53).
#
# You may need to pull on the paper as it reaches the jamming point,
# and/or just abort the program, press the feed button and take the
# last good number.

from __future__ import print_function
from Adafruit_Thermal import *

printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5)

for i in range(0,256,15):
	printer.begin(i)
	printer.println(i)                 # Print heat time
	printer.inverseOn()
	printer.print('{:^32}'.format('')) # Print 32 spaces (inverted)
	printer.inverseOff()

printer.begin() # Reset heat time to default
printer.feed(4)
Ejemplo n.º 49
0
# Enable LED and button (w/pull-up on latter)
GPIO.setup(ledPin, GPIO.OUT)
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# LED on while working
GPIO.output(ledPin, GPIO.HIGH)

# Processor load is heavy at startup; wait a moment to avoid
# stalling during greeting.
# time.sleep(30)

# Print greeting image
printer.feed(1)
printer.printImage(Image.open('40in20out_logo.bmp'), True)
printer.feed(1)
printer.print("40in20out")
printer.feed(1)
printer.print("Presented by...")
printer.feed(1)
printer.printImage(Image.open('totemasset_logo.bmp'), True)
printer.feed(2)
GPIO.output(ledPin, GPIO.LOW)

# Show IP address (if network is available)
try:
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	s.connect(('8.8.8.8', 0))
	printer.print('My IP address is ' + s.getsockname()[0])
        ip = s.getsockname()[0]
	printer.feed(3)
except:
Ejemplo n.º 50
0
data = issueRequestAndDecodeResponse(
    "GET",
    (searchUrl + "count=3&since_id=%s&q=%s" % (lastId, urllib.quote(queryString))),
    None,
    {"Host": host, "User-Agent": agent, "Accept-Encoding": "gzip", "Authorization": "Bearer " + token},
)


# Display results. ---------------------------------------------------------

maxId = data["search_metadata"]["max_id_str"]

for tweet in data["statuses"]:

    printer.inverseOn()
    printer.print(" " + "{:<31}".format(tweet["user"]["screen_name"]))
    printer.inverseOff()

    printer.underlineOn()
    printer.print("{:<32}".format(tweet["created_at"]))
    printer.underlineOff()

    # max_id_str is not always present, so check tweet IDs as fallback
    id = tweet["id_str"]
    if id > maxId:
        maxId = id  # String compare is OK for this

    # Remove HTML escape sequences
    # and remap Unicode values to nearest ASCII equivalents
    printer.print(unidecode(HTMLParser.HTMLParser().unescape(tweet["text"])))
Ejemplo n.º 51
0
# Enable LED and button (w/pull-up on latter)
GPIO.setup(ledPin, GPIO.OUT)
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# LED on while working
GPIO.output(ledPin, GPIO.HIGH)

# Processor load is heavy at startup; wait a moment to avoid
# stalling during greeting.
time.sleep(35)

# Show IP address (if network is available)
try:
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	s.connect(('8.8.8.8', 0))
	printer.print('\nMy IP address is ' + s.getsockname()[0])
	printer.feed(3)
except:
	printer.boldOn()
	printer.println('Network is UNREACHABLE.')
	printer.boldOff()
	printer.print('Connect display and keyboard\n'
	  'for network troubleshooting.')
	printer.feed(3)
	exit(0)

# Print greeting image
printer.printImage(Image.open('gfx/hello.png'), True)
printer.feed(3)
GPIO.output(ledPin, GPIO.LOW)
Ejemplo n.º 52
0
def mapVals(val, inMin, inMax, outMin, outMax):
        toRet = float(outMin + float(outMax - outMin) * float(float(val - inMin) / float(inMax - inMin)))
        return clamp(toRet, outMin, outMax)

def clamp(val, tmin, tmax):
    if val > tmax:
        val = tmax
    if val < tmin:
        val = tmin
    return val

uart.setup("UART2")
printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5)
printer.begin()
printer.upsideDownOn()
printer.feed(3)
printer.print(parse('i am awake and I am MUG (thermal)'))
printer.feed(1)
rPast = 0
rMax = 0 # all-time max sensor reading
rMin = 0 # all-time min sensor reading
WINDOW_SIZE = 30 # size of moving-window avg
noop = 0 # number of intervals passed without a trigger
noop_threshold = 480
emission_threshold = 0.7

while True:
    checkSensor()
    time.sleep(0.5)
Ejemplo n.º 53
0
    printer.print(' high ' + hi)
    printer.print(deg)
    printer.println(' ' + cond)


printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5)
deg = chr(0xf8)  # Degree symbol on thermal printer

# Fetch forecast data from Yahoo!, parse resulting XML
dom = parseString(
    urllib.urlopen('http://weather.yahooapis.com/forecastrss?w=' +
                   WOEID).read())

# Print heading
printer.inverseOn()
printer.print('{:^32}'.format(
    dom.getElementsByTagName('description')[0].firstChild.data))
printer.inverseOff()

# Print current conditions
printer.boldOn()
printer.print('{:^32}'.format('Current conditions:'))
printer.boldOff()
printer.print('{:^32}'.format(
    dom.getElementsByTagName('pubDate')[0].firstChild.data))
temp = dom.getElementsByTagName('yweather:condition')[0].getAttribute('temp')
cond = dom.getElementsByTagName('yweather:condition')[0].getAttribute('text')
printer.print(temp)
printer.print(deg)
printer.println(' ' + cond)
printer.boldOn()
Ejemplo n.º 54
0
# }

# data = {
#     'username': '******',
# 	'password': '******'
# }

# data = urllib.urlencode(data)
# req = urllib2.Request('https://www.urbbox.com.br/admin', data, headers) 
# response = urllib2.urlopen(req)



# Print heading
printer.inverseOn()
printer.print('{:^32}'.format("Abraao e muito foda"))
printer.inverseOff()

# # Print current conditions
# printer.boldOn()
# printer.print('{:^32}'.format('Current conditions:'))
# printer.boldOff()
# printer.print('{:^32}'.format(
#   dom.getElementsByTagName('pubDate')[0].firstChild.data))
# temp = dom.getElementsByTagName('yweather:condition')[0].getAttribute('temp')
# cond = dom.getElementsByTagName('yweather:condition')[0].getAttribute('text')
# printer.print(temp)
# printer.print(deg)
# printer.println(' ' + cond)
# printer.boldOn()
Ejemplo n.º 55
0
   (lastId, urllib.quote(queryString))),
  None,
  {'Host'            : host,
   'User-Agent'      : agent,
   'Accept-Encoding' : 'gzip',
   'Authorization'   : 'Bearer ' + token})


# Display results. ---------------------------------------------------------

maxId = data['search_metadata']['max_id_str']

for tweet in data['statuses']:

  printer.inverseOn()
  printer.print(' ' + '{:<31}'.format(tweet['user']['screen_name']))
  printer.inverseOff()

  printer.underlineOn()
  printer.print('{:<32}'.format(tweet['created_at']))
  printer.underlineOff()

  # max_id_str is not always present, so check tweet IDs as fallback
  id = tweet['id_str']
  if(id > maxId): maxId = id # String compare is OK for this

  # Remove HTML escape sequences
  # and remap Unicode values to nearest ASCII equivalents
  printer.print(unidecode(
    HTMLParser.HTMLParser().unescape(tweet['text'])))
pedidosDB = db.pedidos
clientesDB = db.direcciones


#try:
pedidos = pedidosDB.find({'estatus':'Enviado a tienda'})
#except:


for pedido in pedidos:
  #print(pedido)
  idCliente = pedido['cliente'][0]
  #print(idCliente)	
  cliente = clientesDB.find_one({'owner':idCliente})
  
  printer.print('{:<32}'.format(cliente['nombre']))
  
  printer.print(' ' + '{:<31}'.format(cliente['telefono']))
  printer.print(' ' + '{:<31}'.format(cliente['calle']))
  printer.print('numExt ' + '{:<25}'.format(cliente['numExt']))
  printer.print('numInt ' + '{:<25}'.format(cliente['numInt']))
  printer.print('Col ' + '{:<28}'.format(cliente['colonia']))

  printer.print('total ' + '{:<26}'.format(str(pedido['total'])))
  printer.print('{:<32}'.format(str(pedido['fecha'])))
  sleep(1.5)
  printer.print('\n')
  
  # Remove HTML escape sequences
  # and remap Unicode values to nearest ASCII equivalents
  printer.print('\n')