def resetModem():
    try:
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(onPin, GPIO.OUT)
        GPIO.setup(pwrKey, GPIO.OUT)
        GPIO.setup(statusPin, GPIO.IN)
    except Exception as e:
        pass

    GPIO.output(onPin, GPIO.LOW) # set the GSM ON/OFF pin to low to turn off the modem
    time.sleep(10)
    GPIO.output(onPin, GPIO.HIGH) # set the GSM ON/OFF pin to high to turn on the modem
    time.sleep(5)
    # Then Toggle the power key
    GPIO.output(pwrKey, GPIO.HIGH)
    GPIO.output(pwrKey, GPIO.LOW)
    time.sleep(5)
    GPIO.output(pwrKey, GPIO.HIGH)
    time.sleep(30)
    status = GPIO.input(statusPin)
    try:
        if status == 1:
            subprocess.call(['sudo sakis3g "connect"  DNS="8.8.8.8" APN="CUSTOM_APN" CUSTOM_APN="airtelgprs.com" APN_USER="******" APN_PASS="******" USBINTERFACE="3" OTHER="USBMODEM" USBMODEM="1e0e:9001"'], shell=True)
    except Exception as e:
        print(e)
    time.sleep(5)
    print('GSM Status: ', GPIO.input(statusPin))
Exemple #2
0
def resetModem():

    GPIO.output(
        onPin, GPIO.LOW)  # set the GSM ON/OFF pin to low to turn off the modem
    time.sleep(10)
    GPIO.output(
        onPin,
        GPIO.HIGH)  # set the GSM ON/OFF pin to high to turn on the modem
    time.sleep(5)
    # Then Toggle the power key
    GPIO.output(pwrKey, GPIO.HIGH)
    GPIO.output(pwrKey, GPIO.LOW)
    time.sleep(5)
    GPIO.output(pwrKey, GPIO.HIGH)
    time.sleep(30)
    status = GPIO.input(statusPin)
    dns = '8.8.8.8' if gsmConf.get('DNS') is None else gsmConf.get('DNS')
    apn = 'airtelgprs.com' if gsmConf.get('APN') is None else gsmConf.get(
        'APN')
    apnUser = '******' if gsmConf.get('APN_USER') is None else gsmConf.get(
        'APN_USER')
    apnPass = '******' if gsmConf.get('APN_PASS') is None else gsmConf.get(
        'APN_PASS')
    usbInterface = '3' if gsmConf.get('USBINTERFACE') is None else gsmConf.get(
        'USBINTERFACE')
    usbModem = '1e0e:9001' if gsmConf.get('USBMODEM') is None else gsmConf.get(
        'USBMODEM')
    command = f'sudo sakis3g "connect"  DNS="{dns}" APN="CUSTOM_APN" CUSTOM_APN="{apn}" APN_USER="******" APN_PASS="******" USBINTERFACE="{usbInterface}" OTHER="USBMODEM" USBMODEM="{usbModem}"'
    try:
        if status == 1:
            subprocess.call([command], shell=True)
    except Exception as e:
        LOG.error('Error resetting modem : %s', e)
    time.sleep(5)
    LOG.info('GSM Status: %s', GPIO.input(statusPin))
Exemple #3
0
    def updateOutputUI(self):
        try:
            result = []
            result_pwm = []

            for rpi_output in self.rpi_outputs:
                pin = self.toInt(rpi_output['gpioPin'])
                if rpi_output['outputType']=='regular':
                    val = GPIO.input(pin) if not rpi_output['activeLow'] else (not GPIO.input(pin))
                    result.append({pin:val})
                if rpi_output['outputType']=='pwm':
                    # self._logger.info("outputType is PWM")
                    # self._logger.info("Got pin number: %s",pin)
                    # self._logger.info("PWM_INSTANCES: %s",self.PWM_INSTANCES)
                    for pwm in self.PWM_INSTANCES:
                        if pin in pwm:
                            if 'dutycycle' in pwm:
                                pwmVal = pwm['dutycycle'];
                                val = self.toInt(pwmVal)
                            else:
                                val = 100
                            result_pwm.append({pin:val})
                        # self._logger.info("result_pwm: %s", result_pwm)
            self._plugin_manager.send_plugin_message(self._identifier, dict(rpi_output=result,rpi_output_pwm=result_pwm))
        except Exception as ex:
            template = "An exception of type {0} occurred on updateOutputUI. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            self._logger.warn(message)
            pass
Exemple #4
0
 def __pulse(self, channel):
     clk_state = GPIO.input(self.clk)
     dt_state = GPIO.input(self.dt)
     if clk_state != self.rotaryLastState:
         self.rotaryLastState = clk_state
         if dt_state != clk_state:
             self.menu.change_highlight(1)
         else:
             self.menu.change_highlight(-1)
         self.menu.render()
Exemple #5
0
    def radio_rx_cfg():
        radio_write(0x01, 0x00)
        radio_write(0x01, 0x05)
        dio2 = GPIO.input(sx1276_DIO2)

        while (dio2 != 1):
            dio2 = GPIO.input(sx1276_DIO2)

        result = radio_read(0x01)

        return result
Exemple #6
0
 def relay_sensor_callback(self, _):
     while GPIO.input(self.pin_relay) == self.switch_pin_relay:
         self.relay_send_alert_count += 1
         self.debug_only_output('Confirmations: ' +
                                str(self.relay_send_alert_count))
         sleep(self.poll_time / 1000)
         if self.confirmations <= self.relay_send_alert_count:
             self.relay_send_alert = True
             self.relay_send_alert_count = 0
             self._logger.info("Relay Sensor Triggered!")
             self._plugin_manager.send_plugin_message(
                 self._identifier,
                 dict(title="Relay Sensor",
                      type="error",
                      autoClose=False,
                      msg="Relay Sensor Triggered!"))
             if self.send_webhook:
                 subprocess.Popen(
                     "curl -X POST -H 'Content-Type: application/json' https://maker.ifttt.com/trigger/%s/with/key/%s"
                     % (self.ifttt_applet_name_pin2, self.ifttt_secretkey),
                     shell=True)
                 self.debug_only_output("Pin 2 Sending a webhook to ifttt.")
             if self.pause_print:
                 self.debug_only_output("Pausing print.")
                 self._printer.pause_print()
             if self.gcode_relay:
                 self.debug_only_output("Sending Relay Sensor GCODE")
                 self._printer.commands(self.gcode_relay)
             break
     else:
         self.relay_send_alert = False
         self.relay_send_alert_count = 0
Exemple #7
0
    def send_blink(n_blink):
        sbuff = [0] * 64
        sbuff[0] = 0x7e
        sbuff[1] = 0x8c
        sbuff[2] = 0x8a
        sbuff[3] = 0x92
        sbuff[4] = 0x98
        sbuff[5] = 0x86
        sbuff[6] = 0xa0
        sbuff[7] = 0xe0
        sbuff[8] = 0x8c
        sbuff[9] = 0x8a
        sbuff[10] = 0x92
        sbuff[11] = 0x84
        sbuff[12] = 0xa6
        sbuff[13] = 0x62
        sbuff[14] = 0x61
        ns = random.getrandbits(3)  #radom integer of 3 bits
        nr = (ns + 1) & 0x07
        sbuff[15] = (nr << 5) | (ns << 1) | 0x10
        sbuff[16] = 0xf0
        sbuff[17] = 0xa6
        if n_blink > 0 and n_blink < 255:
            sbuff[18] = n_blink
        else:
            print("WRONG PARAMETERS INSERTED")
            return

        checksum = 0
        for i in range(1, 17):
            checksum += sbuff[i]

        sbuff[61] = (~checksum) + 1
        checksum = 0
        for i in range(17, 61):
            checksum += sbuff[i]

        sbuff[62] = (~checksum) + 1
        sbuff[63] = 0x7e
        #send the packet to the FIFO
        reg_value = radio_read(0x3f)
        radio_write(0x3f, reg_value | 0x10)  #reset FIFO
        radio_tx_cfg()
        for i in range(0, 64):
            radio_write(0, sbuff[i])

        while (GPIO.input(11) == 0):
            time.sleep(0.00001)

        print("INFORMATION FRAME SENT: DEBUG LED BLINK", n_blink, "TIMES")
        print("SEQUENCE NUMBER N(R):", hex(nr))
        reg_value = radio_read(0x3f)
        radio_write(0x3f, reg_value | 0x10)  #reset FIFO
        print("WAITING FOR REPLY...")

        base(4)  ## wai for message with a timeout of 2 seconds
        base(
            0
        )  ## this maintains the radio at the receiver routine after the end of the transmission
        return
Exemple #8
0
def test_input():
    with patch("OPi.GPIO.sysfs") as mock:
        mock.input.return_value = GPIO.HIGH
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(23, GPIO.IN)
        assert GPIO.input(23) == GPIO.HIGH
        mock.input.assert_called_with(14)
Exemple #9
0
 def handlePrinterAction(self,channel):
     try:
         for rpi_input in self.rpi_inputs:
             if channel == self.toInt(rpi_input['gpioPin']) and rpi_input['eventType']=='printer' and \
             ((rpi_input['edge']=='fall') ^ GPIO.input(self.toInt(rpi_input['gpioPin']))):
                 if rpi_input['printerAction'] == 'resume':
                     self._logger.info("Printer action resume.")
                     self._printer.resume_print()
                 elif rpi_input['printerAction'] == 'pause':
                     self._logger.info("Printer action pause.")
                     self._printer.pause_print()
                 elif rpi_input['printerAction'] == 'cancel':
                     self._logger.info("Printer action cancel.")
                     self._printer.cancel_print()
                 elif rpi_input['printerAction'] == 'stopTemperatureControl':
                     self._logger.info("Printer action stoping temperature control.")
                     self.enclosureSetTemperature = 0;
                     self.handleTemperatureControl()
                 for notification in self.notifications:
                     if notification['printerAction']:
                         msg = "Printer action: " +  rpi_input['printerAction'] + " caused by input: " + str(rpi_input['label'])
                         self.sendNotification(msg)
     except Exception as ex:
         template = "An exception of type {0} occurred on handlePrinterAction. Arguments:\n{1!r}"
         message = template.format(type(ex).__name__, ex.args)
         self._logger.warn(message)
         pass
Exemple #10
0
def test_input_and_output():
    with patch("OPi.GPIO.sysfs") as mock:
        mock.input.return_value = GPIO.HIGH
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(23, GPIO.OUT)
        GPIO.output(23, not GPIO.input(23))
        mock.input.assert_called_with(14)
        mock.output.assert_called_with(14, GPIO.LOW)
Exemple #11
0
    def change_battery(code):
        sbuff = [0] * 64
        sbuff[0] = 0x7e
        sbuff[1] = 0x8c
        sbuff[2] = 0x8a
        sbuff[3] = 0x92
        sbuff[4] = 0x98
        sbuff[5] = 0x86
        sbuff[6] = 0xa0
        sbuff[7] = 0xe0
        sbuff[8] = 0x8c
        sbuff[9] = 0x8a
        sbuff[10] = 0x92
        sbuff[11] = 0x84
        sbuff[12] = 0xa6
        sbuff[13] = 0x62
        sbuff[14] = 0x61
        ns = random.getrandbits(3)  #radom integer of 3 bits
        nr = (ns + 1) & 0x07
        sbuff[15] = (nr << 5) | (ns << 1) | 0x10
        sbuff[16] = 0xf0
        sbuff[17] = 0xa8

        sbuff[
            18] = code  #0x00 for only reading / 0xf0 to switch to main / 0xff to switch to backup

        checksum = 0
        for i in range(1, 17):
            checksum += sbuff[i]

        sbuff[61] = (~checksum) + 1
        checksum = 0
        for i in range(17, 61):
            checksum += sbuff[i]

        sbuff[62] = (~checksum) + 1
        sbuff[63] = 0x7e
        #send the packet to the FIFO
        reg_value = radio_read(0x3f)
        radio_write(0x3f, reg_value | 0x10)  #reset FIFO
        radio_tx_cfg()
        for i in range(0, 64):
            radio_write(0, sbuff[i])

        while (GPIO.input(11) == 0):
            time.sleep(0.00001)

        print("INFORMATION FRAME SENT: CHANGE BATTERY CIRCUIT")
        print("SEQUENCE NUMBER N(R):", hex(nr))
        reg_value = radio_read(0x3f)
        radio_write(0x3f, reg_value | 0x10)  #reset FIFO
        print("WAITING FOR REPLY...")

        base(4)  ## wait
        base(
            0
        )  ## this maintains the radio at the receiver routine after the end of the transmission
        return
Exemple #12
0
    def main(self):
        lastVolume = self.volume
        clkLastState = GPIO.input(config.clk)
        newVolume = lastVolume
        try:
            print("Started cattrotar!");
            while True:

                clkState = GPIO.input(config.clk)
                dtState = GPIO.input(config.dt)

                # see if we got a change since last iteration of loop
                if clkState != clkLastState:
                    if dtState != clkState:
                        newVolume += .5
                    else:
                        newVolume -= .5

                    # only if new volume has changed more than .5 and it's different than prior
                    # volume levels do we actually update volume
                    if newVolume % 1 == 0 and lastVolume != newVolume:
                        # reset button state to be up
                        self.button = 0

                        # set volume
                        newVolume = self.setVolume(newVolume)
                        lastVolume = newVolume

                # empty screen after 10 seconds
                if (time.time() - self.last_screen_update) > 10:
                    self.show(' ')

                clkLastState = clkState
                sleep(0.001)

        except KeyboardInterrupt:
            print("\nkeyboard killed the process")

        finally:
            self.show('Bye!')
            sleep(0.5)
            self.show(' ')
            self.show(' ')
            print('cattrotar exiting')
            GPIO.cleanup()
 def pinRead(self, pin):
     #print "pin",pin ,"set to", self.pinUse[pin]
     #print pin ," being read"
     try:
         return GPIO.input(pin)
     except Exception,e: 
         print "Some error reading pin" ,pin
         print str(e)
         return 0
Exemple #14
0
def readGPIO():
  STATUS = 0

  for pin in PIN_PGM:
      B = GPIO.input(pin)
      STATUS = STATUS | B
      STATUS = STATUS << 1
  ##  print "read GPIO char str int" , chr(STATUS+50) ,str(STATUS), STATUS
  return STATUS
Exemple #15
0
    def readNextBit(self):
        # Clock HX711 Digital Serial Clock (PD_SCK).  DOUT will be
        # ready 1us after PD_SCK rising edge, so we sample after
        # lowering PD_SCL, when we know DOUT will be stable.
        GPIO.output(self.PD_SCK, True)
        GPIO.output(self.PD_SCK, False)
        value = GPIO.input(self.DOUT)

        # Convert Boolean to int and return it.
        return int(value)
Exemple #16
0
    def send_devices_info():
        sbuff = [0] * 64
        sbuff[0] = 0x7e
        sbuff[1] = 0x8c
        sbuff[2] = 0x8a
        sbuff[3] = 0x92
        sbuff[4] = 0x98
        sbuff[5] = 0x86
        sbuff[6] = 0xa0
        sbuff[7] = 0xe0
        sbuff[8] = 0x8c
        sbuff[9] = 0x8a
        sbuff[10] = 0x92
        sbuff[11] = 0x84
        sbuff[12] = 0xa6
        sbuff[13] = 0x62
        sbuff[14] = 0x61
        ns = random.getrandbits(3)  #radom integer of 3 bits
        nr = (ns + 1) & 0x07
        sbuff[15] = (nr << 5) | (ns << 1) | 0x10
        sbuff[16] = 0xf0
        sbuff[17] = 0xa2

        checksum = 0
        for i in range(1, 17):
            checksum += sbuff[i]

        sbuff[61] = (~checksum) + 1
        checksum = 0
        for i in range(17, 61):
            checksum += sbuff[i]

        sbuff[62] = (~checksum) + 1
        sbuff[63] = 0x7e
        #send the packet to the FIFO
        reg_value = radio_read(0x3f)
        radio_write(0x3f, reg_value | 0x10)  #reset FIFO
        radio_tx_cfg()
        for i in range(0, 64):
            radio_write(0, sbuff[i])

        while (GPIO.input(11) == 0):
            time.sleep(0.00001)

        print("INFORMATION FRAME SENT: REQUEST DEVICE INFORMATION")
        print("SEQUENCE NUMBER N(R):", hex(nr))
        reg_value = radio_read(0x3f)
        radio_write(0x3f, reg_value | 0x10)  #reset FIFO
        print("WAITING FOR REPLY...")

        base(4)  ## wait for message with a timeout
        base(
            0
        )  ## this maintains the radio at the receiver routine after the end of the transmission
        return
Exemple #17
0
def index():
    #    get_Host_name_IP()
    now = datetime.now()  #.time().strftime("%H:%M")
    hour = now.hour
    minute = now.minute
    weekday = now.weekday()

    pins = Pin.query.order_by(Pin.pin.asc()).all()
    dailyschedule = DailySchedule.query.all()
    weeklyschedule = WeeklySchedule.query.all()
    apis = API.query.all()

    pin_status = {}
    used_pin = []
    for pin in pins:  # read status of pin
        pin_status[pin.pin] = GPIO.input(pin.pin)
        used_pin.append(pin.pin)

    # tracking all ip to access
    if request.remote_addr not in ip_req:
        ip_req.append(request.remote_addr)

    days = [
        "monday", "tuesday", "wednesday", "thursday", "friday", "saturday",
        "sunday"
    ]
    avalible_pins = [
        3, 5, 7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24, 26
    ]
    api_provider = ['openweathermap', 'darksky', 'opencagedata', 'weatherapi']

    for pin in used_pin:  # delete used pin
        avalible_pins.remove(pin)

    dayname = days[weekday]

    isalive = thread.isAlive()

    return render_template("index.html",
                           totalprecip_mm=totalprecip_mm,
                           maxtemp_c=maxtemp_c,
                           apis=apis,
                           api_provider=api_provider,
                           dailyschedule=dailyschedule,
                           weeklyschedule=weeklyschedule,
                           hour=hour,
                           minute=minute,
                           weekday=weekday,
                           pins=pins,
                           pin_status=pin_status,
                           dayname=dayname,
                           avalible_pins=avalible_pins,
                           ip_req=ip_req,
                           isalive=isalive)
Exemple #18
0
 def set_menu(self, menu):
     self.menu = menu
     GPIO.add_event_detect(self.clk, GPIO.BOTH, callback=self.__pulse)
     GPIO.add_event_detect(self.dt, GPIO.BOTH, callback=self.__pulse)
     GPIO.add_event_detect(self.btn,
                           GPIO.RISING,
                           callback=self.__button,
                           bouncetime=200)
     self.rotaryLastState = None
     self.btnLastState = GPIO.input(self.btn)
     self.clkLevel = 0
     self.dtLevel = 0
Exemple #19
0
 def handleGPIOControl(self,channel):
     try:
         for rpi_input in self.rpi_inputs:
             if channel == self.toInt(rpi_input['gpioPin']) and rpi_input['eventType']=='gpio' and \
             ((rpi_input['edge']=='fall') ^ GPIO.input(self.toInt(rpi_input['gpioPin']))):
                 for rpi_output in self.rpi_outputs:
                     if self.toInt(rpi_input['controlledIO']) == self.toInt(rpi_output['gpioPin']) and rpi_output['outputType']=='regular':
                         if rpi_input['setControlledIO']=='toggle':
                             val = GPIO.LOW if GPIO.input(self.toInt(rpi_output['gpioPin']))==GPIO.HIGH else GPIO.HIGH
                         else:
                             val = GPIO.LOW if rpi_input['setControlledIO']=='low' else GPIO.HIGH
                         self.writeGPIO(self.toInt(rpi_output['gpioPin']),val)
                         for notification in self.notifications:
                             if notification['gpioAction']:
                                 msg = "GPIO control action caused by input " + str(rpi_input['label']) + ". Setting GPIO" + str(rpi_input['controlledIO']) + " to: " + str(rpi_input['setControlledIO'])
                                 self.sendNotification(msg)
     except Exception as ex:
         template = "An exception of type {0} occurred on handleGPIOControl. Arguments:\n{1!r}"
         message = template.format(type(ex).__name__, ex.args)
         self._logger.warn(message)
         pass
Exemple #20
0
    def send_supervisory(nr):
        sbuff = [0] * 64
        sbuff[0] = 0x7e
        sbuff[1] = 0x8c
        sbuff[2] = 0x8a
        sbuff[3] = 0x92
        sbuff[4] = 0x98
        sbuff[5] = 0x86
        sbuff[6] = 0xa0
        sbuff[7] = 0xe0
        sbuff[8] = 0x8c
        sbuff[9] = 0x8a
        sbuff[10] = 0x92
        sbuff[11] = 0x84
        sbuff[12] = 0xa6
        sbuff[13] = 0x62
        sbuff[14] = 0x61
        nr = nr & (0x07)
        sbuff[15] = (nr << 5) | 0x1d
        sbuff[16] = 0xf0

        checksum = 0
        for i in range(1, 17):
            checksum += sbuff[i]

        sbuff[61] = (~checksum) + 1
        checksum = 0
        for i in range(17, 61):
            checksum += sbuff[i]

        sbuff[62] = (~checksum) + 1
        sbuff[63] = 0x7e

        #send the packet to th FIFO
        reg_value = radio_read(0x3f)
        radio_write(0x3f, reg_value | 0x10)  #reset FIFO
        radio_tx_cfg()
        for i in range(0, 64):
            radio_write(0, sbuff[i])

        while (GPIO.input(11) == 0):
            time.sleep(0.00001)
        print("SUPERVISORY COMMAND SENT | SEQUENCE NUMBER N(R)", hex(nr))
        reg_value = radio_read(0x3f)
        radio_write(0x3f, reg_value | 0x10)  #reset FIFO
        print("WAITING FOR REPLY...")

        base(4)  ## wai for message with a timeout of 2 seconds
        base(
            0
        )  ## this maintains the radio at the receiver routine after the end of the transmission
        return
 def EncoderCallback(channel):
     global preset
     global oldPreset
     global updateReq
     if not GPIO.input(encB) and preset < 127:
         preset += 1
     elif preset > 0:
         preset -= 1
     else:
         pass
     if oldPreset != preset:
         updateReq = True
         oldPreset = preset
Exemple #22
0
    def watch(self):

        if self.device is not None:
            for event in self.device.read_loop():
                if event.type == 2:
                    if event.value == 1:
                        self._clockwise_tick()
                    elif event.value == -1:
                        self._counterclockwise_tick()
        else:

            while True:
                try:
                    # Switch part
                    if self.sw_callback:
                        if GPIO.input(self.sw) == GPIO.LOW:
                            self._switch_press()
                        else:
                            self._switch_release()

                    # Encoder part
                    clkState = GPIO.input(self.clk)
                    dtState = GPIO.input(self.dt)

                    if clkState != self.clk_last_state:
                        if dtState != clkState:
                            self._clockwise_tick()
                        else:
                            self._counterclockwise_tick()

                    self.clk_last_state = clkState
                    sleep(self.polling_interval / 1000)

                except BaseException as e:
                    logger.info("Exiting...")
                    logger.info(e)
                    GPIO.cleanup()
                    break
        return
    def Buttons():

        global preset, lastbuttontime

        while True:
            now = time.time()
            if not GPIO.input(BTN1) and (now - lastbuttontime) > 0.5:
                lastbuttontime = now
                preset -= 1
                if preset < 0:
                    preset = 127
                LoadSamples()
                #print('BTN1=',GPIO.input(BTN1))

            elif not GPIO.input(BTN2) and (now - lastbuttontime) > 0.5:
                lastbuttontime = now
                preset += 1
                if preset > 127:
                    preset = 0
                LoadSamples()
                #print('BTN2=',GPIO.input(BTN2))

            time.sleep(0.050)
Exemple #24
0
def read_pin(pin):
    state = -1
    if PFIO_MODULE:
        state = PFIO.digital_read(pin)

    if GPIO_MODULE:
        state = GPIO.input(pin)

    if MONITOR_OUT_INVERT:
        if state == 0:
            state = 1
        elif state == 1:
            state = 0
    return (state)
Exemple #25
0
def outFunction(null):
    global Counter

    PIN_CLK_AKTUELL = GPIO.input(PIN_CLK)

    if PIN_CLK_AKTUELL != PIN_CLK_LETZTER:

        if GPIO.input(PIN_DT) != PIN_CLK_AKTUELL:
            Counter += 1
            Richtung = True
        else:
            Richtung = False
            Counter = Counter - 1

        print("Rotation detected: ")

        if Richtung:
            print("Rotational direction: Clockwise")
        else:
            print("Rotational direction: Counterclockwise")

        print("Current position: ", Counter)
        print "------------------------------"
Exemple #26
0
  def io_check(self):
    checks = {}
    if (self.io_check_count >= 65535):
      self.io_check_count = 0
    else:
      self.io_check_count += 1
    logging.debug("IO check " + str(self.io_check_count))
    for name, chan in self.runtime.switch_channels.items():
      result = self.runtime.ct_ios[name].update(GPIO.input(chan))
      # value confirmed
      if result[0]:
        checks[name] = result[1]
    for name, chan in self.runtime.flip_channels.items():
      result = self.runtime.ct_ios[name].update(int (not GPIO.input(chan)))
      if result[0]:
        checks[name] = result[1]
    for name, chan in self.runtime.pir_channels.items():
      result = self.runtime.ct_ios[name].update(GPIO.input(chan))
      # PIR's are special because they like to be on and are only turned off during
      # timed checkups
      if result[0] and result[1] and not self.runtime.last_pir_state[name]:
        checks[name] = result[1]
        self.runtime.last_pir_state[name] = result[1]

    # don't run the temperature power control if there is no such thing.
    try:
      result = self.runtime.temp_fault_sm.update(not GPIO.input(self.runtime.temp_fault))
      if result[0]:
        checks["Temp Power Fault"] = result[1]
    except AttributeError:
      pass
    # notify if any values were changed
    if checks:
      self.notify('event', checks)
    else:
      logging.debug("Noting changed between timed io checks")
def resetModem():
    GPIO.output(
        onPin, GPIO.LOW)  # set the GSM ON/OFF pin to low to turn off the modem
    time.sleep(10)
    GPIO.output(
        onPin,
        GPIO.HIGH)  # set the GSM ON/OFF pin to high to turn on the modem
    time.sleep(5)
    # Then Toggle the power key
    GPIO.output(pwrKey, GPIO.HIGH)
    GPIO.output(pwrKey, GPIO.LOW)
    time.sleep(5)
    GPIO.output(pwrKey, GPIO.HIGH)
    time.sleep(30)
    status = GPIO.input(statusPin)
    try:
        if status == 1:
            subprocess.Popen(
                ['wvdial -C /root/DataLogger/recovery/wvdial.conf'],
                shell=True)
    except Exception as e:
        print(e)
    time.sleep(5)
    print('GSM Status: ', GPIO.input(statusPin))
Exemple #28
0
    def basic_distance(trig_pin, echo_pin, celsius=20):
        """Return an unformatted distance in cm's as read directly from
        RPi.GPIO."""

        speed_of_sound = 331.3 * math.sqrt(1 + (celsius / 273.15))
        GPIO.setup(trig_pin, GPIO.OUT)
        GPIO.setup(echo_pin, GPIO.IN)
        GPIO.output(trig_pin, GPIO.LOW)
        time.sleep(0.1)
        GPIO.output(trig_pin, True)
        time.sleep(0.00001)
        GPIO.output(trig_pin, False)
        echo_status_counter = 1
        while GPIO.input(echo_pin) == 0:
            if echo_status_counter < 1000:
                sonar_signal_off = time.time()
                echo_status_counter += 1
            else:
                raise SystemError("Echo pulse was not received")
        while GPIO.input(echo_pin) == 1:
            sonar_signal_on = time.time()

        time_passed = sonar_signal_on - sonar_signal_off
        return time_passed * ((speed_of_sound * 100) / 2)
Exemple #29
0
 def startFilamentDetection(self):
     self.stopFilamentDetection()
     try:
         for rpi_input in self.rpi_inputs:
             if rpi_input['eventType'] == 'printer' and rpi_input['printerAction'] == 'filament' and self.toInt(rpi_input['gpioPin']) != 0:
                 edge =  GPIO.RISING if rpi_input['edge'] == 'rise' else GPIO.FALLING
                 if GPIO.input(self.toInt(rpi_input['gpioPin'])) == (edge == GPIO.RISING):
                     self._printer.pause_print()
                     self._logger.info("Started printing with no filament.")
                 else:
                     GPIO.add_event_detect(self.toInt(rpi_input['gpioPin']), edge, callback= self.handleFilammentDetection, bouncetime=200)
     except Exception as ex:
         template = "An exception of type {0} occurred on startFilamentDetection. Arguments:\n{1!r}"
         message = template.format(type(ex).__name__, ex.args)
         self._logger.warn(message)
         pass
 def pinRCTime (self,pin):
     reading = 0
     #print "rc pin told to set to output"
     self.pinUpdate(pin,0)
     #print "rc changed to ouput"
     time.sleep(0.1)
     #print "sleep done"
     GPIO.setup(pin,GPIO.IN)
     #print "rc set to input"
     #time.sleep(3)
     #print "sleep 2 done"
     # This takes about 1 millisecond per loop cycle
     while (GPIO.input(pin) == GPIO.LOW) and (reading < 1000):
         reading += 1
     #print "change back to output"
     GPIO.setup(pin,GPIO.OUT)
     self.pinUpdate(pin,0)
     return reading