Esempio n. 1
0
 def play_id(play_id):
     client = MPDClient()
     client.connect(app.config['MPD']['host'], app.config['MPD']['port'])
     client.timeout = None
     client.idletimeout = None
     client.playid(play_id)
     return redirect(url_for('player'))
Esempio n. 2
0
def main():
    """Shows basic usage of the Google Calendar API.

    Creates a Google Calendar API service object and outputs a list of the next
    10 events on the user's calendar.
    """
    if len(sys.argv) < 1:
      raise(NameError('No user added to path'))      
    
    credentials = get_credentials(2)
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('calendar', 'v3', http=http)

    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    eventsResult = service.events().list(
        calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,
        orderBy='startTime').execute()
    events = eventsResult.get('items', [])

    if not events:
        print('No upcoming events found.')
    
    client = mqtt.Client()
    client.connect("54.229.54.240", 1883, 60)
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        loc = 'unknown'
        if 'location' in event:
          loc = event['location']
        client.publish("carai/usr/cal",json.dumps(event))
        client.loop(1) #timeout 1 sec
        print(start, event['summary'],loc)
 def play_id(play_id):
     client = MPDClient()
     client.connect(app.config['MPD']['host'], app.config['MPD']['port'])
     client.timeout = None
     client.idletimeout = None
     client.playid(play_id)
     return redirect(url_for('player'))
Esempio n. 4
0
def run_pi_socket():
    # ssh into pi and run socket script
    host = "raspi2"
    user = "******"
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(
        paramiko.AutoAddPolicy())  # booz allen messes everything up pt. 200012
    client.connect(host, username=user)
    stdin, stdout, stderr = client.exec_command('python socket_test.py')
Esempio n. 5
0
def mqtt_setup():
    global client
    # Create MQTT client and connect to localhost, i.e. the Raspberry Pi running
    # this script and the MQTT server.
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect('localhost', 1883, 60)
    # Connect to the MQTT server and process messages in a background thread.
    client.loop_start()
    # Main loop to listen for button presses.
    printBetter('Script is running, press Ctrl-C to quit...')
    time.sleep(3)
Esempio n. 6
0
    def player_action(player_action):
        client = MPDClient()
        client.connect(app.config['MPD']['host'], app.config['MPD']['port'])
        client.timeout = None
        client.idletimeout = None

        if player_action == 'backward':
            client.previous()
        elif player_action == 'forward':
            client.next()
        elif player_action == 'play':
            client.play()
        elif player_action == 'pause':
            client.pause()

        return redirect(url_for('player'))
    def player_action(player_action):
        client = MPDClient()
        client.connect(app.config['MPD']['host'], app.config['MPD']['port'])
        client.timeout = None
        client.idletimeout = None

        if player_action == 'backward':
            client.previous()
        elif player_action == 'forward':
            client.next()
        elif player_action == 'play':
            client.play()
        elif player_action == 'pause':
            client.pause()

        return redirect(url_for('player'))
Esempio n. 8
0
    def player():
        client = MPDClient()
        client.connect(app.config['MPD']['host'], app.config['MPD']['port'])
        client.timeout = None
        client.idletimeout = None

        splitTemp = client.status()['time']
        split = splitTemp.split(':')

        templateData = {
            'variable': (int(split[0]) * 100) / int(split[1]),
            'status': client.status(),
            'current': client.currentsong(),
            'playlist': client.playlistinfo()
        }

        return render_template('player.html', **templateData)
    def player():
        client = MPDClient()
        client.connect(app.config['MPD']['host'], app.config['MPD']['port'])
        client.timeout = None
        client.idletimeout = None

        splitTemp = client.status()['time']
        split = splitTemp.split(':')

        templateData = {
            'variable': (int(split[0]) * 100) / int(split[1]),
            'status': client.status(),
            'current': client.currentsong(),
            'playlist': client.playlistinfo()
        }

        return render_template('player.html', **templateData)
# 클라이언트가 서버에게서 CONNACK 응답을 받을 때 호출되는 콜백
def on_connect(client, userdata, rc):
    print("Connected with result coe " + str(rc))
    client.subscribe("Entity/SHM/Node/353041080754218/Device/Status")


# 서버에게서 PUBLISH 메시지를 받을 때 호출되는 콜백
def on_message(client, userdata, msg):
    now_time = str(date.datetime.now())
    print("Time: ", now_time)
    print("Topic: ", msg.topic)
    mqtt_data = str(msg.payload)
    split_topic = str(msg.topic).split('/')


logger = logging.getLogger(__name__)

client = mqtt.Client()  # MQTT Client 오브젝트 생성
print("Test Step 01")
client.enable_logger(logger)
print("Test Step 02")
client.on_connect = on_connect  # on_connect callback 설정
print("Test Step 03")
client.on_message = on_message  # on_message callback 설정
print("Test Step 04")
client.connect(broker.strip())  # MQTT 서버에 연결
print("Test Step 05")

client.subscribe(mqtt_topic.strip())

client.loop_forever()
Esempio n. 11
0
    def __init__(self):
        self.POOL_TIME = 40
        self.INACTIVE_LIMIT = 60
        self.TIME_FORMAT = "%d-%m-%Y-%H:%M:%S"
        self.INACTIVE = -1
        self.INIT = 0
        self.DEFAULT_TEMP = 25

        cur_dir = os.path.abspath(__file__)
        cur_dir = os.path.dirname(cur_dir)
        with open(f'{cur_dir}/config.yml') as conf:
            config = yaml.safe_load(conf)

        # Load config from test_server
        username = config['IO_USERNAME']
        key = config['IO_KEY']
        pump = config['feed']['output']
        sensor = config['feed']['input']['sensor']
        tempHumid = config['feed']['input']['tempHumid']

        # Load config from real servers
        bbc = config['realServer']
        bbc_username = bbc['USERNAME']
        bbc_key = bbc['KEY']
        pump_bbc = bbc['relay']
        sensor_bbc = bbc['soil']
        tempHumid_bbc = bbc['dht']

        self.logApp = LogApp()
        self.predictor = PredictionModel()

        # Test server
        self.client = {username: MQTTClient(username, key)}
        # Real servers
        self.client.update({
            bbc_username[i]: MQTTClient(bbc_username[i], bbc_key[i])
            for i in range(len(bbc_key))
        })

        sensors = self.logApp.getSensors()

        self.pump = {key: {'owner': username, 'value': None} for key in pump}
        self.pump.update({
            pump_bbc['feedId']: {
                'owner': pump_bbc['IO_OWNER'],
                'value': None
            }
        })

        self.sensor = {
            key: {
                'owner': username,
                'value': None,
                'sysID': sensors['soilMoisture'][key]['sysID'],
                'rcvTime': self.INACTIVE
            }
            for key in sensor
        }
        self.sensor.update({
            sensor_bbc['feedId']: {
                'owner': sensor_bbc['IO_OWNER'],
                'value': None,
                'sysID':
                sensors['soilMoisture'][sensor_bbc['feedId']]['sysID'],
                'rcvTime': self.INACTIVE
            }
        })

        self.tempHumid = {
            key: {
                'owner': username,
                'temp': None,
                'humid': None,
                'sysID': sensors['dht'][key]['sysID'],
                'rcvTime': self.INACTIVE
            }
            for key in tempHumid
        }
        self.tempHumid.update({
            tempHumid_bbc['feedId']: {
                'owner': tempHumid_bbc['IO_OWNER'],
                'temp': None,
                'humid': None,
                'sysID': sensors['dht'][tempHumid_bbc['feedId']]['sysID'],
                'rcvTime': self.INACTIVE
            }
        })

        self.writeHistory_loop = Thread(target=self.writeSensorHistory)
        self.writeHistory_loop.daemon = True

        self.autoStop_loop = Thread(target=self.autoStop)
        self.autoStop_loop.daemon = True

        self.wateringHistory = {key: None for key in self.pump}
        self.sensorSendingCheck = True

        def writeWateringHistory(pump_id, waterLevel):
            # Get time
            timestamp = int(datetime.now().timestamp())
            # time_only = timestamp.strftime("%H:%M:%S")
            # timestamp = timestamp.strftime(self.TIME_FORMAT)

            # Get sensor value
            status = self.logApp.getPumpStatus(pump_id)
            auto = status['auto']
            moisture = self.sensor[status['soilMoistureID']]['value']
            humid = self.tempHumid['dht0001']['humid']
            temp = self.tempHumid['dht0001']['temp']

            if waterLevel == '1' and self.wateringHistory[pump_id] is None:
                # Create new record for pump_id
                self.wateringHistory[pump_id] = {
                    'autoStart': auto,
                    'autoEnd': None,
                    'startTime': timestamp,
                    'endTime': None,
                    'moistureStart': moisture,
                    'moistureEnd': None,
                    'humidityStart': humid,
                    'humidityEnd': None,
                    'temperatureStart': temp,
                    'temperatureEnd': None
                }
            if waterLevel == '0' and self.wateringHistory[pump_id] is not None:
                # Update record for pump_id
                self.wateringHistory[pump_id]['autoEnd'] = auto
                self.wateringHistory[pump_id]['endTime'] = timestamp
                self.wateringHistory[pump_id]['moistureEnd'] = moisture
                self.wateringHistory[pump_id]['humidityEnd'] = humid
                self.wateringHistory[pump_id]['temperatureEnd'] = temp
                # Write this record to firebase
                self.logApp.writeWateringHistory(pump_id,
                                                 self.wateringHistory[pump_id],
                                                 timestamp)
                # Set record of this pump_id to None
                self.wateringHistory[pump_id] = None

        def connected(client):
            for feed_id in self.sensor:
                if client._username == self.sensor[feed_id]['owner']:
                    client.subscribe(feed_id=feed_id,
                                     feed_user=self.sensor[feed_id]['owner'])
                    client.receive(feed_id)

            for feed_id in self.tempHumid:
                if client._username == self.tempHumid[feed_id]['owner']:
                    client.subscribe(
                        feed_id=feed_id,
                        feed_user=self.tempHumid[feed_id]['owner'])
                    client.receive(feed_id)

            for feed_id in self.pump:
                if client._username == self.pump[feed_id]['owner']:
                    client.subscribe(feed_id=feed_id)
                    client.receive(feed_id)

#self.pumpHistory = {key: {autoEnd:None, autoStart:  None, ...} for key in pump}

        def message(client, feed_id, payload):
            payload = json.loads(payload)
            value = payload['data']
            Printout.i(
                'new value',
                'Feed {0} received new value: {1}'.format(feed_id, value))

            if (feed_id in self.pump):
                self.pump[feed_id]['value'] = value
                self.logApp.changePumpStatus(feed_id, value)
                writeWateringHistory(feed_id, value)

            elif (feed_id in self.sensor):
                self.sensor[feed_id]['value'] = value
                self.sensor[feed_id]['rcvTime'] = time.time()
                self.logApp.changeSoilMoisute(feed_id, value)
                self.changeWaterlevel(feed_id)

                # Predict if counter >=
                # 1 + (number of active dht that has the same sysID as this sensor)
                # n_dht = len(self.getActiveTempHumidSensor(feed_id))
                # if self.sensor[feed_id]['counter'] >= 1 + n_dht:
                #     self.changeWaterlevel(feed_id)
                #     self.sensor[feed_id]['counter'] = 0
                # self.sensorSendingCheck = True

            elif (feed_id in self.tempHumid):
                value = value.split('-')
                self.tempHumid[feed_id]['temp'] = value[0]
                self.tempHumid[feed_id]['humid'] = value[1]
                self.tempHumid[feed_id]['rcvTime'] = time.time()
                self.logApp.changeTempHumid(feed_id, value[0], value[1])

                # Predict for sensor that has counter >=
                # 1 + (number of active dht that has the same sysID as this sensor)
                # n_dht = len(self.getActiveTempHumidSensor(feed_id, is_soil=False))
                # for sensor_id in self.getActiveSoilSensor(feed_id):
                #     self.sensor[sensor_id]['counter'] += 1
                #     if(self.sensor[sensor_id]['counter'] >= 1 + n_dht):
                #         self.changeWaterlevel(sensor_id)
                #         self.sensor[sensor_id]['counter'] = 0
                # self.sensorSendingCheck = True

        def disconnected(client):
            Printout.i('client', 'Disconnected from Adafruit IO')
            sys.exit(1)

        def subscribe(client, userdata, mid, granted_qos):
            # This method is called when the client subscribes to a new feed.
            Printout.i('client', 'Subscribe to pumps and sensors')

        for client in self.client.values():
            client.on_connect = connected
            client.on_message = message
            client.on_disconnect = disconnected
            client.on_subscribe = subscribe
            client.connect()

        self.writeHistory_loop.start()
        self.autoStop_loop.start()

        for client in self.client.values():
            client.loop_background()