def Text(name, theme): printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) # Test inverse on & off printer.inverseOn() # printer.println("Inverse ON") # Test character double-height on & off #printer.doubleHeightOn() printer.println("On vous recommande le livre suivant :") #printer.doubleHeightOff() printer.inverseOff() # Set justification (right, center, left) -- accepts 'L', 'C', 'R' # printer.justify('R') # printer.println("Right justified") printer.justify('C') printer.println(name) printer.inverseOn() # printer.println("Inverse ON") # Test character double-height on & off #printer.doubleHeightOn() printer.println("Le thème de ce livre est :") #printer.doubleHeightOff() printer.inverseOff() printer.justify('C') printer.println(theme) # printer.justify('L') # printer.println("Left justified") # Test more styles printer.boldOn() printer.println("Bold text") printer.boldOff() printer.underlineOn() printer.println("Underlined text") printer.underlineOff() printer.setSize('L') # Set type size, accepts 'S', 'M', 'L' printer.println("Large") printer.setSize('M') printer.println("Medium") printer.setSize('S') printer.println("Small") printer.justify('C') printer.println("normal\nline\nspacing") printer.setLineHeight(50) printer.println("Taller\nline\nspacing") printer.setLineHeight() # Reset to default printer.justify('L') # Barcode examples printer.feed(1) # CODE39 is the most common alphanumeric barcode printer.printBarcode("ADAFRUT", printer.CODE39) printer.setBarcodeHeight(100) # Print UPC line on product barcodes printer.printBarcode("123456789123", printer.UPC_A) printer.sleep() # Tell printer to sleep printer.wake() # Call wake() before printing again, even if reset printer.setDefault() # Restore printer to defaults
def generate_post(): with open('/home/yuri/mashbotv2/cleaned.txt') as f: text = f.read() text_model = markovify.Text(text, state_size=2) mash_text = text_model.make_short_sentence(129) # was 140 wrapped_text = textwrap.fill(mash_text, 32) output_text = "@acoluthon " + mash_text printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.setDefault() printer.justify('L') printer.feed(3) printer.boldOn() printer.setSize('M') printer.println("Mash Note") printer.setSize('S') printer.boldOff() printer.println(wrapped_text) printer.feed(2) # Write the status to a file, for debugging with open('/home/yuri/mashbotv2/history.txt', 'a') as f: f.write('mashed: ' + mash_text + ' | tweeted: ' + output_text + '\n') return output_text
def printadvice(): # Initialize the printer. Note this will take a few seconds for the printer # to warm up and be ready to accept commands (hence calling it explicitly vs. # automatically in the initializer with the default auto_warm_up=True). printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) fortune = random.choice(hints) printer.justify('C') printer.println(' ___ ___ ') printer.println(' /| <⋈> |\ ') printer.println(' /_| : |_\ ') printer.println(' | : | ') printer.println(' |___: __| ') printer.println(' __ __ ') printer.println('| \ \ ___ // ___') printer.println('| |/ . \ <_-<') printer.println('|_|_|_|\___/ /__/') printer.println(' ___ _ ') printer.println('|_ _|<_> ___ ___ ') printer.println(' | | | || . \<_-< ') printer.println(' |_| |_|| _//__/ ') printer.println(' |_| ') printer.feed(1) printer.boldOn() printer.println(fortune) printer.boldOff() printer.feed(2) printer.feed(3) printer.sleep() # Tell printer to sleep printer.wake() # Call wake() before printing again, even if reset printer.setDefault() # Restore printer to defaults
# 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(15) # Show IP address (if network is available) try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 0)) device.boldOn() device.print('My IP address is ' + s.getsockname()[0]) device.boldOff() device.feed(3) except: device.boldOn() device.println('Network is unreachable.') device.boldOff() device.print('Connect display and keyboard\n' 'for network troubleshooting.') device.feed(3) exit(0) # Print greeting image device.printImage(Image.open('gfx/hello.png'), True) device.feed(3)
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()
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)
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)
return gray if __name__ == '__main__': # new videocapture object cap = cv2.VideoCapture(0) # Create a Adafruit_Thermal object that we can use for printing printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) # python-tesseract initialization api = tesseract.TessBaseAPI() api.SetOutputName("hacker_u") api.Init(".","eng",tesseract.OEM_DEFAULT) api.SetPageSegMode(tesseract.PSM_AUTO) printer.boldOn() # Make text bold printer.setSize('L') # Set type size, accepts 'S', 'M', 'L' printer.justify('C') # Center the text to leave lots of whitespace while(True): ''' Prompt the user to enter some text to be recognized by python-tesseract ''' text_to_print = raw_input("Enter text: ") # Alert user that we are printing print("Printing...") ''' Print the user's text out ''' printer.println(text_to_print) time.sleep(1)
def main(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) 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) # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) try: service = build('tasks', 'v1', credentials=creds) tasklists = service.tasklists().list(maxResults=10).execute().get( 'items', []) p = Adafruit_Thermal() p.setDefault() p.setSize('M') p.justify('C') if not tasklists: p.println('No task lists found.') return else: p.println('Tasks') p.setSize('S') # print('Task lists:') for tasklist in tasklists: # print(u'{0} ({1})'.format(tasklist['title'], tasklist['id'])) tasks = service.tasks().list( tasklist=tasklist['id']).execute().get('items', []) for task in sorted(tasks, key=lambda t: t.get('order', '')): task_title = task.get('title', '-') task_status = task.get('status', None) task_due = task.get('due', None) if task_due is not None: task_due_s = dateutil.parser.parse(task_due).strftime( config.date_format) p.boldOn() p.underlineOn() p.justify('R') p.println(task_due_s) p.boldOff() p.underlineOff() p.justify('L') p.print('[ ] ') p.println(task_title) p.println('') # make some space except HttpError as err: print(err)
def main(): printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) deg = chr(0xf8) # Degree symbol on thermal printer events = get_events() # Print heading printer.setSize('M') printer.justify('C') printer.println( datetime.datetime.today().date().strftime("%A, %B %-d, %Y")) printer.justify('L') printer.setSize('S') # Print schedule printer.boldOn() printer.underlineOn() printer.justify('C') printer.println("Today's Schedule") printer.justify('L') printer.underlineOff() printer.boldOff() printer.feed(1) if not events: printer.println('No scheduled events today.') printer.feed(1) for event in events: start = dateutil.parser.parse(event['start'].get( 'dateTime', event['start'].get('date'))).strftime("%-I:%M%p") end = dateutil.parser.parse(event['end'].get( 'dateTime', event['end'].get('date'))).strftime("%-I:%M%p") location = event.get('location', '') printer.println(event['summary']) if start == end: if location: printer.println(start + ", " + location) else: printer.println(start) else: if location == "": printer.println(start + " - " + end) else: printer.println(start + " - " + end + ", " + location) printer.feed(1) printer.feed(1) # Print weather weather = get_weather() printer.boldOn() printer.underlineOn() printer.justify('C') printer.println("Today's Weather") printer.justify('L') printer.underlineOff() printer.boldOff() printer.feed(1) printer.println("Temperature: " + str(weather.temp_now) + ". Feels like " + str(weather.feels_like_now)) printer.feed(1) printer.println("Today: " + weather.weather_today) printer.feed(1) printer.println("Tonight: " + weather.weather_tonight) printer.feed(1) downcase_first = lambda s: s[:1].lower() + s[1:] if s else '' printer.println("Tomorrow: " + weather.weather_tomorrow + " Tomorrow night, " + downcase_first(weather.weather_tomorrow_night)) printer.feed(1) printer.feed(2)
# we want to see if lastSplitIdx equals the last index of enumerate(spaceIndexes) # if they DON'T equal, we want to append the rest of our message if spaceIndexes[lastSplitIdx] != spaceIndexes[-1]: # start at the lastSplitIdx startIdx = spaceIndexes[lastSplitIdx] # go from the startIdx to the end element = fortune[startIdx:] # push to queue queue.append(element) # ADAFRUIT INITIALIZATION from Adafruit_Thermal import * # grab printer printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) printer.feed(1) # whitespace at the top of the print printer.justify('C') # justify center printer.setSize('M') # Mid size text printer.boldOn() # bold the text in this # from our built queue array, go through and print each line. for element in queue: printer.println(element) printer.boldOff() # remove the bold printer.feed(5) # whitespace at the bottom of the print printer.sleep() # Tell printer to sleep printer.wake() # Call wake() before printing again, even if reset printer.setDefault() # Restore printer to defaults
p.setDefault() p.setSize('L') p.println('Todo') for i in api.items.all(): # print(i) date_str = i['due'] if date_str: date_str = date_str['date'] if date_str: due_date = dateutil.parser.parse(date_str) else: due_date = None p.boldOn() p.underlineOn() p.justify('L') p.print('[ ] ') if due_date: p.println(due_date.strftime(config.date_format)) else: p.println('') p.boldOff() p.underlineOff() p.justify('R') content = unicodedata.normalize( 'NFD', i['content']).encode('ascii', 'ignore')
class Printer(Thread): def __init__(self, headers): Thread.__init__(self) self.headers = headers self.config = json.load(open('/home/pi/bitrepublic/Config.json')) self.printerCount = self.config["printer"]["count"] self.maxRequestPerSecond = self.config["printer"][ "maxRequestPerSecond"] self.img = Image.open(self.config["printer"]["img"]) self.address = self.config["requests"]["consume"]["Address"] self.minInterval = self.config["printer"]["minInterval"] self.maxInterval = max( 1, 2 * self.printerCount * self.maxRequestPerSecond - self.minInterval) self.printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) tmp = min(self.minInterval, self.maxInterval) self.maxInterval = max(self.minInterval, self.maxInterval) self.minInterval = tmp #print("minInterval : "+str(minInterval)) #print("maxInterval : "+str(maxInterval)) printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) #print("Setup: success") self.t = Terminal() print(self.t.italic('Hi there! : I\'m the Printer')) def grabBitsoilAndPrint(self): print(self.t.italic('Printer : is there any new bitsoil ?')) r = requests.get(self.address, headers=self.headers) #send the get request. if r.status_code == 200: #checks if the server respond jdata = r.json() if jdata["data"] != False: #checks if there is data in the output of the server. print(jdata["data"]) myDate = (jdata["data"]["date"]) myKey = (jdata["data"]["publicKey"]) myAmount = (jdata["data"]["bitsoil"]) print(self.t.italic('Printer : Yes ! so I\'ve to do...')) self.printReceipt(myDate, myKey, myAmount) else: print(r.status_code) def printReceipt(self, myDate, myKey, myAmount): self.printer.wake( ) # Call wake() before printing again, even if reset. self.printer.justify('C') self.printer.boldOn() self.printer.println(myDate) self.printer.boldOff() self.printer.println('') self.printer.justify('C') self.printer.println(myKey) self.printer.printImage(self.img, True) self.printer.setSize('M') self.printer.justify('C') self.printer.println(format(myAmount, 'f') + ' Bitsoil') self.printer.println('--------------------------------') self.printer.feed(1) self.printer.sleep() # Tell printer to sleep. self.printer.setDefault() # Restore printer to defaults. self.printer.reset( ) #if you don't reset, the printer starts to f**k up the receipt. def run(self): while True: self.grabBitsoilAndPrint( ) #checks if there is bitsoils available to print, and if there is, it prints it. t = random.randint(self.minInterval, self.maxInterval) print( self.t.italic('Printer : Pfiouf... See you in ' + str(t) + ' seconds')) time.sleep(t) #wait for x seconds before re-checking for bitsoils.
# Test character double-width on & off printer.doubleWidthOn() printer.println("Double Width ON") printer.doubleWidthOff() # Set justification (right, center, left) -- accepts 'L', 'C', 'R' printer.justify('R') printer.println("Right justified") printer.justify('C') printer.println("Center justified") printer.justify('L') printer.println("Left justified") # Test more styles printer.boldOn() printer.println("Bold text") printer.boldOff() printer.underlineOn() printer.println("Regular underlined text") printer.underlineOff() printer.underlineOn(2) printer.println("Heavy underlined text") printer.underlineOff() printer.strikeOn() printer.println("Strike through text") printer.strikeOff()
def main(): printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) deg = chr(0xf8) # Degree symbol on thermal printer events = get_events() # Print heading printer.setSize('M') printer.justify('C') printer.println( datetime.datetime.today().date().strftime("%A, %B %-d, %Y") ) printer.justify('L') printer.setSize('S') # Print schedule printer.boldOn() printer.underlineOn() printer.justify('C') printer.println("Today's Schedule") printer.justify('L') printer.underlineOff() printer.boldOff() printer.feed(1) if not events: printer.println('No scheduled events today.') printer.feed(1) for event in events: start = dateutil.parser.parse(event['start'].get('dateTime', event['start'].get('date'))).strftime("%-I:%M%p") end = dateutil.parser.parse(event['end'].get('dateTime', event['end'].get('date'))).strftime("%-I:%M%p") location = event.get('location', '') printer.println(event['summary']) if start == end: if location: printer.println(start + ", " + location) else: printer.println(start) else: if location == "": printer.println(start + " - " + end) else: printer.println(start + " - " + end + ", " + location) printer.feed(1) printer.feed(1) # Print weather weather = get_weather() printer.boldOn() printer.underlineOn() printer.justify('C') printer.println("Today's Weather") printer.justify('L') printer.underlineOff() printer.boldOff() printer.feed(1) printer.println("Temperature: " + str(weather.temp_now) + ". Feels like " + str(weather.feels_like_now)) printer.feed(1) printer.println("Today: " + weather.weather_today) printer.feed(1) printer.println("Tonight: " + weather.weather_tonight) printer.feed(1) downcase_first = lambda s: s[:1].lower() + s[1:] if s else '' printer.println("Tomorrow: " + weather.weather_tomorrow + " Tomorrow night, " + downcase_first(weather.weather_tomorrow_night)) printer.feed(1) printer.feed(2)
# Test character double-height on & off printer.doubleHeightOn() printer.println("Double Height ON") printer.doubleHeightOff() # Set justification (right, center, left) -- accepts 'L', 'C', 'R' printer.justify('R') printer.println("Right justified") printer.justify('C') printer.println("Center justified") printer.justify('L') printer.println("Left justified") # Test more styles printer.boldOn() printer.println("Bold text") printer.boldOff() printer.underlineOn() printer.println("Underlined text") printer.underlineOff() printer.setSize('L') # Set type size, accepts 'S', 'M', 'L' printer.println("Large") printer.setSize('M') printer.println("Medium") printer.setSize('S') printer.println("Small") printer.justify('C')
def __print_new_account_info(account_number, pin_number, tos): printer = Adafruit_Thermal("/dev/ttyS0", 19200, timeout=60) printer.setSize('M') printer.justify('C') printer.println("1st Regional Bunny Bank\n\n") printer.boldOn() printer.println("================================") printer.boldOff() printer.boldOn() printer.boldOn() printer.println("================================") printer.boldOff() printer.println("================================") printer.boldOff() printer.setSize('S') printer.justify('C') printer.println("Here at 1st Regional BB") printer.println("we're proud to provide you") printer.println("with words when you're") printer.println("struggling to find them.") printer.justify('C') printer.println("================================") printer.justify('C') printer.setSize('S') printer.println("Account #") printer.setSize('M') printer.println(account_number) printer.setSize('S') printer.println("Pin #") printer.setSize('M') printer.println(pin_number) printer.setSize('S') printer.println("================================") printer.justify('L') printer.println("\n") printer.println("With your new account you") printer.println("have the following options:") printer.boldOn() printer.println("1. Deposit") printer.boldOff() printer.println("Your balance is increased by one") printer.println("and the poem is printed.") printer.boldOn() printer.println("2. Withdraw Personal") printer.boldOff() printer.println("Your balance is not affected") printer.println("and the poems are printed") printer.boldOn() printer.println("3. Withdraw Community") printer.boldOff() printer.println("Your balance is decreased by x") printer.println("and the poems are printed") printer.println("\n\n\n") printer.println("--------------------------------") printer.println("--------------------------------") printer.println(text_format(TERMS_OF_SERVICE)) printer.println("--------------------------------") printer.feed(30)