<commit_before>"""
The package 'sensor' is responsible for handling
sensor input i.e. reading the FSR.

Needs to be run as root to access the GPIO pins.

Mostly copied from https://gist.github.com/ladyada/3151375
"""



import time, os, sys
import config

# fall back to randomly generated sensor values if GPIO is not available
try:
  import RPi.GPIO as GPIO
except ImportError:
  #TODO: print -> log...
  print("WARNING: no RPi module available, falling back to dummy GPIO")

  import random

  class GPIO_dummy():

    # this is quite dirty
    def input(self, foo):
      return random.randint(0,1)

    # override all other functions to return 0
    def __getattr__(self, *a):
      return lambda *x: 0


  GPIO = GPIO_dummy()

GPIO.setmode(GPIO.BCM)

# pin setup constants. see also: http://pinout.xyz
#TODO: should these be read from the config?
SPICLK = 18
SPIMISO = 23
SPIMOSI = 24
SPICS = 25
#mcp = Adafruit_MCP3008.MCP3008(clk = SPICLK, cs = SPICS, miso = SPIMISO, mosi = SPIMOSI)


class Sensor():
  # set up SPI interface pins and read configuration
  def __init__(self, cfg_dict = None):

    if cfg_dict is None:
      # use default configuration
      cfg_dict = config.get_config_dict()

    self.calibration = cfg_dict["calibration"]

    GPIO.setup(SPIMOSI, GPIO.OUT)
    GPIO.setup(SPIMISO, GPIO.IN)
    GPIO.setup(SPICLK, GPIO.OUT)
    GPIO.setup(SPICS, GPIO.OUT)
  
  # advance the ADC clock by one
  def _adc_tick(self, clk = SPICLK):
    GPIO.output(clk, True)
    GPIO.output(clk, False)
  
  # read from  the ADC
  def _read_adc(self, adc_num, 
      clockpin = SPICLK, mosipin = SPIMOSI, misopin = SPIMISO, cspin = SPICS): 
  
    if (adc_num > 7) or (adc_num < 0):
      return -1
  
    GPIO.output(cspin, True)
    GPIO.output(clockpin, False)
    GPIO.output(cspin, False)
  
    command_out = adc_num
    command_out |= 0x18 # start bit + single-ended bit (what does this mean?)
    command_out <<= 3
  
    for i in range(5):
      #print(str(bin(command_out & 0x80)) + " " + str(bool(command_out & 0x80)))
      if(command_out & 0x80):
        GPIO.output(mosipin, True)
      else:
        GPIO.output(mosipin, False)
      command_out <<=1
      self._adc_tick()
  
    adc_out = 0
    for i in range(12):
      self._adc_tick(clockpin)
  
      adc_out <<= 1
  
      if GPIO.input(misopin):
        adc_out |= 0x1
  
    GPIO.output(cspin, True)
    adc_out >>= 1
    return adc_out
  
  
  # a function that generates random numbers in the same range
  # as the real adc, for testing purposes.
  
  def _dummy_adc(self):
    import random
    import time
    from math import floor
    prev = 0
    t = time.time()
    while True:
      prev += (random.randrange(100) - 20) * int(floor(time.time() - t))
      prev %= 1024
      t = time.time()
      yield prev
  
  
  """
  The function that returns the sensor value after averaging,
  this is supposed to be called externally.
  """
  #TODO
  def poll(self, averaging_time = 10, avg_interval = 0.01):
    fun = self._read_adc
    #fun = self._dummy_adc
    start = time.time()
    res = 0
    n = 0
    while time.time() - start < averaging_time:
      res += fun()
      n += 1
      time.sleep(avg_interval)
    #res = fun()
    res /= 1.0 * n
    print("poll result: " + str(res) + " ({} averages)".format(n))
    return res

if __name__ == "__main__":
  #tol = 3

  fsr_adc = 0

  s = Sensor()<commit_msg>Read sensor configuration from config dict.<commit_after>"""
The package 'sensor' is responsible for handling
sensor input i.e. reading the FSR.

Needs to be run as root to access the GPIO pins.

Mostly copied from https://gist.github.com/ladyada/3151375
"""



import time, os, sys
import config

# fall back to randomly generated sensor values if GPIO is not available
try:
  import RPi.GPIO as GPIO
except ImportError:
  #TODO: print -> log...
  print("WARNING: no RPi module available, falling back to dummy GPIO")

  import random

  class GPIO_dummy():

    # this is quite dirty
    def input(self, foo):
      return random.randint(0,1)

    # override all other functions to return 0
    def __getattr__(self, *a):
      return lambda *x: 0


  GPIO = GPIO_dummy()

GPIO.setmode(GPIO.BCM)

# pin setup constants. see also: http://pinout.xyz
#TODO: should these be read from the config?
SPICLK = 18
SPIMISO = 23
SPIMOSI = 24
SPICS = 25
#mcp = Adafruit_MCP3008.MCP3008(clk = SPICLK, cs = SPICS, miso = SPIMISO, mosi = SPIMOSI)


class Sensor():
  # set up SPI interface pins and read configuration
  def __init__(self, cfg_dict = None):

    if cfg_dict is None:
      # use default configuration
      cfg_dict = config.get_config_dict()

    self.calibration = cfg_dict["calibration"]

    GPIO.setup(SPIMOSI, GPIO.OUT)
    GPIO.setup(SPIMISO, GPIO.IN)
    GPIO.setup(SPICLK, GPIO.OUT)
    GPIO.setup(SPICS, GPIO.OUT)
  
  # advance the ADC clock by one
  def _adc_tick(self, clk = SPICLK):
    GPIO.output(clk, True)
    GPIO.output(clk, False)
  
  # read from  the ADC
  def _read_adc(self, adc_num, 
      clockpin = SPICLK, mosipin = SPIMOSI, misopin = SPIMISO, cspin = SPICS): 
  
    if (adc_num > 7) or (adc_num < 0):
      return -1
  
    GPIO.output(cspin, True)
    GPIO.output(clockpin, False)
    GPIO.output(cspin, False)
  
    command_out = adc_num
    command_out |= 0x18 # start bit + single-ended bit (what does this mean?)
    command_out <<= 3
  
    for i in range(5):
      #print(str(bin(command_out & 0x80)) + " " + str(bool(command_out & 0x80)))
      if(command_out & 0x80):
        GPIO.output(mosipin, True)
      else:
        GPIO.output(mosipin, False)
      command_out <<=1
      self._adc_tick()
  
    adc_out = 0
    for i in range(12):
      self._adc_tick(clockpin)
  
      adc_out <<= 1
  
      if GPIO.input(misopin):
        adc_out |= 0x1
  
    GPIO.output(cspin, True)
    adc_out >>= 1
    return adc_out
  
  
  # a function that generates random numbers in the same range
  # as the real adc, for testing purposes.
  
  def _dummy_adc(self):
    import random
    import time
    from math import floor
    prev = 0
    t = time.time()
    while True:
      prev += (random.randrange(100) - 20) * int(floor(time.time() - t))
      prev %= 1024
      t = time.time()
      yield prev
  
  
  """
  The function that returns the sensor value after averaging,
  this is supposed to be called externally.
  """
  #TODO
  def poll(self, averaging_time = 10, avg_interval = 0.01):
    fun = self._read_adc
    #fun = self._dummy_adc
    start = time.time()
    res = 0
    n = 0
    while time.time() - start < averaging_time:
      res += fun()
      n += 1
      time.sleep(avg_interval)
    #res = fun()
    res /= 1.0 * n
    print("poll result: " + str(res) + " ({} averages)".format(n))
    return res

if __name__ == "__main__":
  #tol = 3

  fsr_adc = 0

  cfg = config.get_config_dict()

  s = Sensor(cfg)
{'fraction_non_alphanumeric': 0.10904061726597758, 'fraction_numerical': 0.021546076575920805, 'mean_word_length': 2.6387711864406778, 'pattern_counts': {'":': 2, '<': 19, '<?xml version=': 0, '>': 11, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '612612', 'n_tokens_mistral': 2575, 'n_tokens_neox': 2415, 'n_words': 728}