Advertisement
ToinasMaker

Untitled

Oct 3rd, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.22 KB | None | 0 0
  1. """Port of the Adafruit NeoPixel library to python using the FTDI MPSSE.
  2.  
  3. Learn more about NeoPixels here:
  4.  http://learn.adafruit.com/adafruit-neopixel-uberguide/overview
  5.  
  6. This library is meant to be used with a FT232H USB to MPSSE chip or cable, like
  7. the C232HM-EDHSL-0 here:
  8.  http://www.ftdichip.com/Products/Cables/USBMPSSE.htm
  9.  
  10. This library requires the libmpsse library to be installed with python support:
  11.  https://code.google.com/p/libmpsse/
  12.  
  13. Created by Tony DiCola (tony@tonydicola.com)
  14. Released under an MIT license (http://opensource.org/licenses/MIT)
  15.  
  16. """
  17.  
  18. import itertools
  19. import operator
  20. import time
  21. import csv
  22. from mpsse import *
  23. import csv
  24. import pandas as pd
  25. import numpy
  26. from IPython.display import display as ds
  27.  
  28. hashtag1 = "#IntelMakers"
  29. hashtag2 = "#GiraMexicoPorSiempre"
  30. hashtag3= "#ToinasMakerRegresa"
  31.  
  32. intel_blue=[0,0,255]
  33. black=[0,0,0]
  34. white=[255,255,255]
  35. red=[255,0,0]
  36. # Open/create a file to append data to
  37.  
  38.  
  39. #csvFile = open('result.csv', 'a')
  40. #Use csv writer
  41.  
  42. filename='/home/upsquared/Adafruit_NeoPixel_FTDI/tweet.csv'
  43. csvFile = open('/home/upsquared/Adafruit_NeoPixel_FTDI/tweet.csv', 'rb')
  44. csvWriter = csv.writer(csvFile)
  45.  
  46. imec_image=[1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,
  47. 0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
  48. 0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
  49. 1,1,1,1,0,0,0,1,0,0,0,0,0,1,1,1,
  50. 0,0,0,1,1,0,1,1,0,0,0,0,0,1,1,1,
  51. 0,0,0,1,0,1,0,1,0,0,0,0,0,1,0,1,
  52. 0,0,0,1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1,1,1,1,1,1,1,0,0,0,
  82.     0,0,0,1,1,2,2,2,2,2,2,2,1,1,0,0,
  83.     0,0,0,1,1,2,2,2,2,2,2,2,1,1,0,0,
  84.     0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,
  85.     0,0,0,1,1,2,1,1,2,1,1,2,1,1,0,0,
  86.     0,0,0,1,1,2,1,1,2,1,1,2,1,1,0,0,
  87.     0,0,0,1,1,2,2,2,2,2,2,2,1,1,0,0,
  88.     0,0,0,0,1,1,2,2,2,2,2,1,1,0,0,0,
  89.     0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,
  90.     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  91.     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  92.     0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,
  93.     0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,
  94.     0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,
  95.     0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0]
  96.  
  97. # Bit values which represent the zero and one bit pulses.
  98. _ZERO = bytearray([0b11100000])
  99. _ONE  = bytearray([0b11111000])
  100.  
  101.  
  102. def _build_byte_lookup():
  103.     """Return lookup table to map from every byte value 0-255 and the associated
  104.     raw SPI data."""
  105.     lookup = {}
  106.     for i in range(256):
  107.         value = bytearray()
  108.         for j in range(7, -1, -1):
  109.             if ((i >> j) & 1) == 0:
  110.                 value += _ZERO
  111.             else:
  112.                 value += _ONE
  113.         lookup[i] = value
  114.     return lookup
  115.  
  116. _byte_lookup = _build_byte_lookup()
  117.  
  118. def get_default_mpsse(speed_mhz):
  119.     """Open the first MPSSE device found and return it.  Throws an exception if
  120.     no MPSSE device is found."""
  121.     from mpsse import MPSSE
  122.     mpsse = MPSSE(SPI0, speed_mhz, MSB)
  123.     if mpsse is None:
  124.         RuntimeError('Could not find a connected MPSSE device!')
  125.     return mpsse
  126.  
  127. def color(r, g, b):
  128.     """Convert an RGB triplet of 0-255 values to a 24 bit representation."""
  129.     if r < 0 or r > 255 or g < 0 or g > 255 or b < 0 or b > 255:
  130.         raise ValueError('Color values must be 0 to 255.')
  131.     return (r << 16) | (g << 8) | b
  132.  
  133. def color_to_rgb(c):
  134.     """Convert a 24 bit color to RGB triplets."""
  135.     return ((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF)
  136. def _encode_color_grb(c):
  137.     """Encode an RGB tuple into NeoPixel GRB 24 byte SPI bit stream."""
  138.     return _byte_lookup[c[1]] + _byte_lookup[c[0]] + _byte_lookup[c[2]]
  139.  
  140. def _encode_color_rgb(c):
  141.     """Encode an RGB tuple into NeoPixel RGB 24 byte SPI bit stream."""
  142.     return _byte_lookup[c[0]] + _byte_lookup[c[1]] + _byte_lookup[c[2]]
  143.  
  144. class Adafruit_NeoPixel(object):
  145.    
  146.     def __init__(self, n, mpsse=None, neo_rgb=False, neo_khz400=False):
  147.         """Create set of NeoPixels.
  148.  
  149.         The only required parameter is the number of NeoPixels.  By default the
  150.         first MPSSE device found will be used, and it is assumed to be NeoPixels
  151.         which support 800khz GRB signals.  Set either neo_rgb or neo_khz400
  152.         keywoard parameters to True to use RGB or 400 khz NeoPixels respectively.
  153.  
  154.         """
  155.         print('starting Adafruit_NeoPixel class')
  156.         self._n = n
  157.         self._pixels = [0] * n
  158.         # Initialize the mpsse to a default one if not explicitly set.
  159.         if mpsse is None:
  160.             # Default to 6mhz, unless overridden to 3mhz.
  161.             speed = 3000000 if neo_khz400 else 6000000
  162.             mpsse = get_default_mpsse(speed)
  163.         self.setMPSSE(mpsse)
  164.         # Default to GRB encoding, unless overridden to RGB.
  165.         self._encode = _encode_color_rgb if neo_rgb else _encode_color_grb
  166.         self._brightness = 1.0
  167.         self._lastupdate = 0
  168.  
  169.     def close(self):
  170.         """Close the NeoPixel MPSSE connection."""
  171.         if self._mpsse is not None:
  172.             self._mpsse.Close()
  173.  
  174.     def show(self):
  175.         """Write the current pixel data to the NeoPixels."""
  176.         # Ensure there's at least a 50 micro-second delay between show calls.
  177.         delta = time.time() - self._lastupdate
  178.         if delta < 0.00005:
  179.             time.sleep(0.00005 - delta)
  180.         print('starting show')
  181.         self._mpsse.Start()
  182.         # Scale pixels based on brightness and accumulate raw SPI bitstream.
  183.         rgb = itertools.imap(color_to_rgb, self._pixels)
  184.         scaled = itertools.imap(lambda c: (int(c[0] * self._brightness),
  185.                            int(c[1] * self._brightness),
  186.                            int(c[2] * self._brightness)),
  187.                     rgb)
  188.         encoded = itertools.imap(self._encode, scaled)
  189.         # Send data to the wire.
  190.         self._mpsse.Write(str(reduce(operator.add, encoded)))
  191.         self._mpsse.Stop()
  192.         self._lastupdate = time.time()
  193.  
  194.     def setMPSSE(self, mpsse):
  195.         """Change the MPSSE device associated with this NeoPixel instance."""
  196.         if mpsse is None:
  197.             raise ValueError('MPSSE is null.')
  198.         self._mpsse = mpsse
  199.  
  200.     def setPixelColorRGB(self, n, r, g, b):
  201.         """Update pixel at position n to the provided RGB color."""
  202.         self.setPixelColor(n, color(r, g, b))
  203.  
  204.     def setPixelColor(self, n, c):
  205.         """Update pixel at position n to the provided 24 bit RGB color."""
  206.         self._checkIndex(n)
  207.         if not isinstance(c, int):
  208.             raise ValueError('Expected integer value for color.')
  209.         self._pixels[n] = c
  210.  
  211.     def setBrightness(self, b):
  212.         """Scale brightness of NeoPixels to provided value that is between 0 and
  213.         1.0.  A value of 0 is completely dark and 1.0 is normal color brightness.
  214.         Note that brightness is only reflected in the final output shown to the
  215.         hardware and not getPixels or getPixelColor."""
  216.         if b < 0.0 or b > 1.0:
  217.             raise ValueError('Brightness must be 0 to 1.0.')
  218.         self._brightness = b
  219.  
  220.     def getPixels(self):
  221.         """Return all the pixels as an array of 24 bit RGB colors."""
  222.         return self._pixels
  223.  
  224.     def numPixels(self):
  225.         """Return the number of NeoPixels."""
  226.         return self._n
  227.  
  228.     def getPixelColor(self, n):
  229.         """Return the 24 bit RGB color of the pixel at position n."""
  230.         self._checkIndex(n)
  231.         return self._pixels[n]
  232.  
  233.     def _checkIndex(self, n):
  234.         if n < 0 or n >= self._n:
  235.             raise ValueError('Pixel id {0} is outside the range of expected values.'.format(n))
  236.  
  237. def Image_Setup():
  238.        
  239.     """device = Adafruit_NeoPixel(256)     
  240.     device.setBrightness(0.01)"""
  241.  
  242.  
  243.     intel_blue=[0,0,255]
  244.     black=[0,0,0]
  245.     white=[255,255,255]
  246.     red=[255,0,0]
  247.     print "I am spy"
  248.    
  249.     image = []
  250.     for idx in range(len(spy_image)):
  251.         if spy_image[idx] == 0:
  252.             image.append(white)
  253.         if spy_image[idx]== 1:
  254.             image.append(intel_blue)
  255.         if spy_image[idx]== 2:
  256.             image.append(black)
  257.     return image
  258.  
  259. def Translate_Image(image_in):
  260.     image_out=[]
  261.     for idx in range(len(image_in)):
  262.         if image_in[idx] == 0:
  263.             image_out.append(white)
  264.         if image_in[idx]== 1:
  265.             image_out.append(intel_blue)
  266.         if image_in[idx]== 2:
  267.             image_out.append(black)
  268.     return image_out
  269.    
  270. def Free_Image_Setup():
  271.     """device = Adafruit_NeoPixel(256)     
  272.     device.setBrightness(0.01)"""
  273.  
  274.  
  275.     intel_blue=[0,0,255]
  276.     black=[0,0,0]
  277.     white=[255,255,255]
  278.     red=[255,0,0]
  279.  
  280.     free_image = Translate_Image(imec_image)
  281.     print "I am free"
  282.     return free_image
  283.  
  284. def printdiffs(df_in)
  285.     df_in = find_diffs(df_in)
  286.     return df_in
  287.    
  288. def find_diffs(df_in):
  289.     df_latest = pd.read_csv(filename)
  290.     # print("old frame is:\n{}".format(df_in)) 
  291.     # print("newdata frame is:\n{}".format(df_latest))
  292.     print 'old dataframe size is' + str(df_in.size)
  293.     print 'new dataframe size is' + str(df_latest.size)
  294.     diff_df = pd.merge(df_latest, df_in, how='outer', indicator='Exist')
  295.  
  296.     diff_df = diff_df.loc[diff_df['Exist'] != 'both']
  297.     print 'new dataframe size is' + str(diff_df.size)
  298.    
  299.     if diff_df.size > 0:
  300.         print 'diff found' + str(diff_df.size)
  301.         print("old frame is:\n{}".format(diff_df)) 
  302.         # print str(diff_df.size)
  303.         ds_list = df_latest.values[-1].tolist()
  304.         print ds_list[1]
  305.         #print "just the value" + str(df_latest[1])
  306.    
  307.     return diff_df
  308.  
  309. def blit(image, img_width, location, frame_size):
  310.     frame=[black] * frame_size ** 2
  311.     vert_offset=0
  312.  
  313.     img_lines = [image[x:x+img_width] for x in range(0,len(image),img_width)]
  314.     for line in img_lines:
  315.         for idx, value in enumerate(line):
  316.         coord = idx+vert_offset+(location[0] % frame_size)+((location[1] % frame_size)*frame_size)
  317.         # HANDLE EDGE SCROLLING
  318.         #print coord, idx, vert_offset, (vert_offset+(location[1]*frame_size)+frame_size)-1, location, frame_size
  319.         if (coord > (vert_offset+(location[1]*frame_size)+frame_size)-1):
  320.         coord = coord - frame_size
  321.  
  322.         coord = coord % (frame_size ** 2)
  323.             frame[coord] = value
  324.         vert_offset += frame_size
  325.     return frame
  326.  
  327. def display(width, frame):
  328.  
  329.     lines = [frame[x:x+width] for x in range(0,len(frame),width)]
  330.     flipped_frame =[]
  331.     for idx,line in enumerate(lines):
  332.     if idx % 2 == 0:
  333.         flipped_frame+=reversed(line)
  334.     else:
  335.         flipped_frame+=line
  336.  
  337.     for idx, color in enumerate(flipped_frame):
  338.     device.setPixelColorRGB(idx, color[0], color[1], color[2])
  339.     device.show()
  340.  
  341. def Vertical_Scroll(image):
  342.     x=0
  343.     y=0
  344.     vert=1
  345.     horiz=0
  346.     while y < 16:
  347.             #frame = blit(image, 3, [x,int(y)], 16)
  348.         frame = blit(image, 16, [x,int(y)], 16)
  349.         print frame    
  350.         display(16, frame)
  351.         time.sleep(0.2)
  352.         y+=1
  353.        
  354. def Horizontal_Scroll(image):
  355.     x=0
  356.     y=0
  357.     vert=0
  358.     horiz=1
  359.    
  360.     while x < 16:
  361.         if x == 0:
  362.             time.sleep(5)
  363.             print "Show before scroll "+ str(x) + " times"
  364.             #frame = blit(image, 3, [x,int(y)], 16)
  365.         frame = blit(image, 16, [x,int(y)], 16)
  366.         print "me "+ str(x) + " times"
  367.         display(16, frame)
  368.             time.sleep(0.2)
  369.         x+=1
  370.  
  371.  
  372.  
  373. if __name__ == "__main__":
  374.     device = Adafruit_NeoPixel(256)
  375.     device.setBrightness(0.01)
  376.     df_last = pd.DataFrame()
  377.     df_in = pd.DataFrame()
  378.     df_in = pd.read_csv(filename)  
  379.  
  380.     i=0
  381.     imageToDisplay=[]
  382.  
  383.     while True:  
  384.         print("Polling Tweets")
  385.         imageToDisplay=Free_Image_Setup()
  386.         print("Wait 10 seconds to check")
  387.         Horizontal_Scroll(imageToDisplay)
  388.         df_last= printdiffs(df_in)
  389.         time.sleep(10)
  390.         i = i +1
  391.         print ("tweet caught " + str(df_last.size))
  392.         if (df_last.size > 0):          
  393.             imageToDisplay=Image_Setup()
  394.             print("tweet received")
  395.             Horizontal_Scroll(imageToDisplay)
  396.        
  397.        
  398.  
  399.     """device = Adafruit_NeoPixel(256)     
  400.     device.setBrightness(0.01)
  401.     df_last = pd.DataFrame()
  402.     df_in = pd.DataFrame()
  403.     df_in = pd.read_csv(filename)    
  404.     i=0
  405.    
  406.     while True:  
  407.         print("Polling Tweets")
  408.         df_in= printdiffs(df_in)
  409.         time.sleep(7)
  410.         i = i +1
  411.    
  412.         if (df_in.size >> 1):          
  413.             imageToDisplay=Image_Setup()
  414.             print("tweet received")
  415.             print(imageToDisplay)
  416.             Horizontal_Scroll(imageToDisplay)
  417.         else:
  418.             imageToDisplay=Free_Image_Setup()
  419.             print("no tweet")
  420.             print(imageToDisplay)
  421.             Horizontal_Scroll(imageToDisplay)
  422.  
  423.         #time.sleep(0.5)
  424.     #Go back and make sure that when there is more than one  tweet we display all"""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement