Beispiel #1
0
def main():
    MyClient = pymongo.MongoClient('localhost', 27017)
    db = MyClient.ibmmab
    collection = db.analysisdatas
    enda = norge_klima()

    for item in enda:
        translate_article(item)
        if item.text == "NA":
            continue
        try:
            author = item.authors[0]
        except Exception:
            author = "NA"
        postable = {
            "text": item.text.replace("\n", " "),
            "title": item.title,
            "author": author,
            "url": item.url,
            "scrape_date": moment.utcnow().format('YYYYMMDDhhmmss'),
            "publish_date": item.publish_date,
            "createdAt": moment.utcnow().format('YYYYMMDDhhmmss')
        }
        post = collection.insert_one(postable)
        print("Posted")
    def test_devices_delete_email_with_get(self):
        expected_devices = [
            {
                'tipo': 'gcm',
                'id': 'dummy',
                'fecha_registro': moment.utcnow().isoformat()
            },
            {
                'tipo': 'email',
                'id': '*****@*****.**',
                'fecha_registro': moment.utcnow().isoformat()
            }
        ]
        self.mongo_db.devices.insert_many(expected_devices)

        response = self.app.get('/0/dispositivos?tipo=email&[email protected]&borrar=1')

        self.assertEqual('application/json', response.mimetype)
        self.assertEqual(200, response.status_code)

        del expected_devices[1]['_id']
        expected_devices[1]['mensaje'] = 'El dispositivo ha sido borrado con éxito'

        data = json.loads(response.data.decode())
        self.assertEqual(expected_devices[1], data[0])

        self.assertEqual(1, self.mongo_db.devices.count())
Beispiel #3
0
 def test_get_schedule_values_list(self):
     from tangier_api.api import ScheduleConnection, TESTING_SITE
     connection = ScheduleConnection()
     today = moment.utcnow().strftime("%Y-%m-%d")
     three_months_ago = moment.utcnow().add(months=-2).strftime("%Y-%m-%d")
     schedule_list = connection.get_schedule_values_list(
         site_ids=[TESTING_SITE, TESTING_SITE],
         start_date=three_months_ago,
         end_date=today)
     self.assertTrue(
         len(schedule_list) != 0,
         generate_empty_list_error_response(sys._getframe().f_code.co_name,
                                            'schedule_list'))
Beispiel #4
0
 def test_get_schedule(self):
     from tangier_api.api import ScheduleConnection, TESTING_SITE
     connection = ScheduleConnection()
     today = moment.utcnow().strftime("%Y-%m-%d")
     three_months_ago = moment.utcnow().add(months=-2).strftime("%Y-%m-%d")
     schedule = xmlmanip.XMLSchema(
         connection.get_schedule(site_id=TESTING_SITE,
                                 start_date=three_months_ago,
                                 end_date=today))
     schedule_list = schedule.search(location__contains='')
     self.assertTrue(
         len(schedule_list) != 0,
         generate_empty_list_error_response(sys._getframe().f_code.co_name,
                                            'schedule_list'))
Beispiel #5
0
 def test_async_get_schedules(self):
     from tangier_api.async_api import AsyncScheduleConnection
     from tangier_api.api import TESTING_SITE
     connection = AsyncScheduleConnection()
     today = moment.utcnow().strftime("%Y-%m-%d")
     three_months_ago = moment.utcnow().add(months=-2).strftime("%Y-%m-%d")
     site_ids = [TESTING_SITE * 3]
     request_list = connection.generate_request_list(
         three_months_ago, today, site_ids)
     schedule_list = connection.get_schedules(request_list)
     self.assertTrue(
         len(schedule_list) != 0,
         generate_empty_list_error_response(sys._getframe().f_code.co_name,
                                            'schedule_list'))
Beispiel #6
0
def writeTrainingRow(grouped_docs, route, writer, count):
    event = getEventFromRoute(grouped_docs, route)
    quality_score = route.get("rt", -1)

    vehicle_count = 0
    for venue in grouped_docs["venues"]:
        if "trk" in venue["ct"]:
            vehicle_count = vehicle_count + 1

    print(route["_id"])
    hours_since_last_supply = calculateHoursSinceSupply(moment.utcnow(), getSupplyDates(grouped_docs, route))
    if not hours_since_last_supply:
        hours_since_last_supply = -1

    writer.writerow([
        scenario_type,
        calculateDistance(route),
        scenario_total_population[count],
        scenario_number_of_requests[count],
        scenario_total_infant_population[count],
        scenario_total_aged_population[count],
        scenario_emergency_level[count],
        scenario_Hours_since_last_supply[count],
        quality_score,
        vehicle_count,
        calculateHoursSinceDisaster(event),
        scenario_optimal_number_of_trucks,
        scenario_ideal_distribution[count]
    ])
Beispiel #7
0
 def send_frame(self, client):
     global TIMER
     global IS_PROCESSING
     global DID_NOT_SEND
     if IS_PROCESSING:
         # Set this flag to True, so that after processing is complete that frame is sent
         DID_NOT_SEND = True
     else:
         # set this flag back to false so that if previous was True, that case is handled
         DID_NOT_SEND = False
         if client.frame_to_send.value['frame']['probes']['null'] == [] and client.frame_to_send.value['frame']['probes']['directed'] == []:
             # means there is nothing to send or nothing was captured between that interval
             print(
                 "Nothing to send! No Probes were captured in the last interval/cycle.")
         else:
             # send the frame on the publish and reset it back to empty
             print(self.mqtt_client.connected)
             # add timestamp to the frame to help in creating files
             client.frame_to_send.value["timestamp"] = str(
                 moment.utcnow())
             # add device mac_address
             client.frame_to_send.value["deviceMacID"] = self.device_mac_address
             json_in_str = json.dumps(client.frame_to_send.value)
             self.mqtt_client.publish_data(json_in_str)
             # reset the frame back to initial value
             client.frame_to_send.value = {
                 'frame': {'probes': {'directed': [], 'null': []}}}
     TIMER = TIMER + self.refresh_interval
     timer_thread = threading.Timer(
         TIMER - time.time(), self.send_frame, [client])
     timer_thread.daemon = True
     timer_thread.start()
Beispiel #8
0
    def insert_many(cls, mongo_db, reports):
        update_time = moment.utcnow().timezone(CONFIG['moment']['timezone']).isoformat()

        projection = {
            '_id': 0,
            'hash': 1,
        }
        for field in ['hash', 'fuente'] + list(cls.get_fields()):
            projection[field] = 1

        class_collection = cls.get_mongo_collection()
        unique_fields = cls.get_unique_fields()

        for report in reports:
            find_query = {field: report[field] for field in unique_fields}
            row = mongo_db[class_collection].find_one(find_query, projection)

            if row == report:
                continue

            report['actualizacion'] = update_time

            if row is None:
                mongo_db[class_collection].insert_one(report)
            else:
                update_query = {field: row[field] for field in unique_fields}

                mongo_db[class_collection].update_one(
                    update_query,
                    {'$set': report}
                )

            if '_id' in report:
                del report['_id']
Beispiel #9
0
    def build_frame_to_send(self, client, timestamp, rssi, mac_id, ssid=None):
        global IS_PROCESSING
        global DID_NOT_SEND

        print(f'{timestamp} {rssi} {mac_id} {ssid}')
        # Set the flag to True to tell others using the global object to wait till processing is complete
        IS_PROCESSING = True
        if ssid is not None:
            # this means it is a directed probe request
            client.frame_to_send.value['frame']['probes']['directed'].append({'timestamp':  str(
                moment.date(timestamp)), 'rssi': rssi, 'mac_id': mac_id, 'ssid': ssid.strip()})
        else:
            # this means it is a null probe request
            client.frame_to_send.value['frame']['probes']['null'].append({'timestamp':  str(
                moment.date(timestamp)), 'rssi': rssi, 'mac_id': mac_id, 'ssid': None})
        # Set this flag back to False to tell others using the global object that processing is complete and the object is usable
        IS_PROCESSING = False

        # TODO: Handle errors!!!
        # IF Did not send because it was still processing, now send and reset back the frame object back to empty
        if DID_NOT_SEND:
            # add timestamp to the frame to help in creating files
            client.frame_to_send.value["timestamp"] = str(
                moment.utcnow())
            # add device mac_address
            client.frame_to_send.value["deviceMacID"] = self.device_mac_address
            self.mqtt_client.client.publish(
                'frame_topic', json.dumps(client.frame_to_send.value))
            client.frame_to_send.value = {
                'frame': {'probes': {'directed': [], 'null': []}}}
            DID_NOT_SEND = False
Beispiel #10
0
 def test_utcnow_function(self):
     d = moment.utcnow()
     now = datetime.utcnow()
     self.assertEquals(d.year, now.year)
     self.assertEquals(d.month, now.month)
     self.assertEquals(d.day, now.day)
     self.assertEquals(d.hour, now.hour)
     self.assertEquals(d.second, now.second)
Beispiel #11
0
 def test_utcnow_function(self):
     d = moment.utcnow()
     now = datetime.utcnow()
     self.assertEquals(d.year, now.year)
     self.assertEquals(d.month, now.month)
     self.assertEquals(d.day, now.day)
     self.assertEquals(d.hour, now.hour)
     self.assertEquals(d.second, now.second)
Beispiel #12
0
def parse_popularity_data(popularity_data, timezone):
    """Parse popularity information to timestamps in the respective timezone"""
    popularity, waiting_time = [], []
    includes_waiting_time = False

    for day in popularity_data:
        weekday = day[0]
        p = []
        w = []

        # Create timestamps for each hour of the week and set popularity and waiting time to 0 by default since the
        # returned popularity array doesn't necessarily cover all 24 hours of a day but only relevant hours
        for h in range(24):
            timestamp = str(moment.utcnow().timezone(timezone).replace(
                weekday=weekday,
                hours=h,
                minutes=0,
                seconds=0
            ))

            p.append(dict(timestamp=timestamp, popularity=0))
            w.append(dict(timestamp=timestamp, waitingTime=0))

        if day[1] is not None:
            for p_info in day[1]:
                timestamp = str(moment.utcnow().timezone(timezone).replace(
                    weekday=weekday,
                    hours=p_info[0],
                    minutes=0,
                    seconds=0
                ))
                index = next((i for i, item in enumerate(p) if item['timestamp'] == timestamp), -1)
                p[index]['popularity'] = p_info[1]

                # check if the waiting string is available and convert to minutes
                if len(p_info) > 5:
                    includes_waiting_time = True
                    w[index]['waitingTime'] = parse_waiting_time_data(p_info[3])

        popularity += p
        waiting_time += w

    return \
        sorted(popularity, key=lambda x: x['timestamp']), \
        sorted(waiting_time, key=lambda x: x['timestamp']) if includes_waiting_time else None
Beispiel #13
0
    def parse_result(r):
        data = r['data']
        p = get_nested_value(data, 6, 84, 7, 1)
        time_zone = get_nested_value(data, 31, 1, 0, 0)
        timestamp = moment.utcnow().timezone(time_zone).replace(minutes=0,
                                                                seconds=0)

        return dict(id=r['id'],
                    data=dict(popularity=p, timestamp=str(timestamp)))
Beispiel #14
0
def postrequest(request):
    post_data = {
        'users': 'Rocky',
        'id': random.randint(1, 999),
        'createdAt': str(moment.utcnow())
    }
    response = requests.post('https://reqres.in/api/users', data=post_data)
    # geodata = response.json()
    json_data = json.dumps(post_data)
    return HttpResponse(request, json_data, content_type='application/json')
class EditEventForm(Form):
    date = DateField(
        'Date',
        default=moment.utcnow(),
        validators=[
            DataRequired()
        ],
    )
    time = SelectField(
        'Time',
        choices=[("4:00 PM", '4:00 PM'), ("4:15 PM", '4:15 PM'), ("4:30 PM", '4:30 PM'), ("4:45 PM", '4:45 PM'), ("5:00 PM", '5:00 PM')],
    )
    def test_devices_delete_gcm_with_get(self):
        expected_devices = [
            {
                'tipo': 'gcm',
                'id': 'dummy',
                'fecha_registro': moment.utcnow().isoformat()
            },
            {
                'tipo': 'email',
                'id': '*****@*****.**',
                'fecha_registro': moment.utcnow().isoformat()
            }
        ]
        self.mongo_db.devices.insert_many(expected_devices)

        response = self.app.get('/0/dispositivos?tipo=gcm&id=dummy&borrar=1')

        self.assertEqual('application/json', response.mimetype)
        self.assertEqual(400, response.status_code)
        self.assertEqual('[]', response.data.decode())
        self.assertEqual(2, self.mongo_db.devices.count())
Beispiel #17
0
def get_scatter_data(timespan):
    """Send tweet sentiment to scatter plot"""
    print "In our JSON route" + session.get("ticker")
    ticker = session.get("ticker")
    current_stock = Stock.query.get(ticker)
    tweets = current_stock.get_tweets()
    stocks = Stock.query.all()

    # tweets_json = json.dumps(tweets, default=lambda o: o.__dict__)

    # now = moment.utcnow().timezone("US/Eastern")
    result = []
    s = Sentiment(stocks)
    sentiment = None
    negative = ['0.0', '0.1', '0.2', '0.3', '0.4', '0.5']
    positive = ['0.6', '0.7', '0.8', '0.9', '1.0']

    for tweet in tweets:
        #create a moment that represents now - 24 hours
        day_ago = moment.utcnow().timezone("US/Eastern").subtract(hours=24)
        # convert unicode created_at to string
        created_at = unicodedata.normalize('NFKD', tweet.created_at).encode('ascii', 'ignore')
        # format created_at string to ISO 8610
        created_at_str = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y'))
        # create a moment from the string
        created_at = moment.date(created_at_str, 'YYYY-MM-DD HH:mm:ss')
        # convert timezone of moment from UTC to Eastern time
        created_at_final = created_at.utcnow().timezone("US/Eastern")
        print created_at_final > day_ago
        if tweet.text.count('$') == 1 and tweet.retweeted_status is None and created_at_final > day_ago:
            # Convert tweet text from unicode to text
            tweet_text = unicodedata.normalize('NFKD', tweet.text).encode('ascii', 'ignore')
            # Get the sentiment of the tweet retured in either 'positive' or 'negative'
            sentiment_str = s.get_tweet_sentiment(tweet_text)
            if sentiment_str == 'positive':
                sentiment = random.choice(positive)
            if sentiment_str == 'negative':
                sentiment = random.choice(negative)
            created_at = unicodedata.normalize('NFKD', tweet.created_at).encode('ascii', 'ignore')
            # Sun Jun 05 17:09:07 +0000 2016
            created_at_str = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y'))
            # Below 4 lines returns duplicate timestamps... need a way to convert to US/EST timezone
            # create a moment from the string
            # created_at = moment.date(created_at_str, 'YYYY-MM-DD HH:mm:ss')
            # convert timezone of moment from UTC to Eastern time
            # created_at_final = created_at.utcnow().timezone("US/Eastern")
            print "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"
            print created_at_str
            print "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"
            result.append({'datetime': created_at_str, 'sentiment': sentiment})
    #sort dictionary by datetime
    sorted_result = sorted(result, key=lambda k: k['datetime'])
    return json.dumps(sorted_result)
Beispiel #18
0
def is_good_tweet(tweet):
    """Ignore tweets with more than 1 $ symbol, retweets, and anything older than 1 day"""
    #create a moment that represents now - 24 hours
    day_ago = moment.utcnow().timezone("US/Eastern").subtract(hours=24)
    # convert unicode created_at to string
    created_at = unicodedata.normalize('NFKD', tweet.created_at).encode('ascii', 'ignore')
    # format created_at string to ISO 8610
    created_at_str = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y'))
    # create a moment from the string
    created_at = moment.date(created_at_str, 'YYYY-MM-DD HH:mm:ss')
    # convert timezone of moment from UTC to Eastern time
    created_at_final = created_at.utcnow().timezone("US/Eastern")
    print created_at_final > day_ago
    return tweet.text.count('$') == 1 and tweet.retweeted_status is None and created_at_final > day_ago
Beispiel #19
0
 def process_output_line(self, output_line, build_frame_to_send):
     # example output line -45,02:7a:f7:c7:1c:fa or -45,7,02:7a:f7:c7:1c:fa,SSID
     timestamp = str(moment.utcnow().date)
     split_values = output_line.split(",")
     if len(split_values) == 2:
         # this means it has no ssid
         build_frame_to_send(
             self, timestamp, split_values[0], split_values[1].strip())
     elif len(split_values) == 3:
         build_frame_to_send(
             self, timestamp, split_values[0], split_values[1].strip(), split_values[2])
     else:
         # error
         self.bugsnag.notify(Exception("Unknown message from esp"), metadata={
                             "message": output_line})
         print("Unknown message from esp")
class Event(Model):
    student = ForeignKeyField(model=User, backref='events', null=True)
    instructor = ForeignKeyField(model=User, backref='events')
    date = DateField(default=moment.utcnow())
    time = TimeField(default=datetime.time(14, 0, 0))
    duration = CharField(default="15")
    notes = CharField(max_length=256, default="Bleep Bloop")

    class Meta:
        database = DATABASE

    @classmethod
    def create_event(cls, instructor, date, time):
        try:
            cls.create(instructor=instructor, date=date, time=time)
        except IntegrityError:
            raise
Beispiel #21
0
 def start_send_frame(self, client):
     global TIMER
     if len(client.detections) != 0:
         print(max(client.detections))
         detections = max(client.detections)
         client.detections.clear()
         frame = {
             "deviceMacId": self.device_mac_address,
             "detections": detections,
             "timestamp": str(moment.utcnow())
         }
         json_string = json.dumps(frame)
         self.mqtt_client.publish_data(json_string)
     TIMER = TIMER + self.refresh_interval
     timer_thread = threading.Timer(TIMER - time.time(),
                                    self.start_send_frame, [client])
     timer_thread.daemon = True
     timer_thread.start()
Beispiel #22
0
    def post(request, **kwargs):
        files_form = EditUserFileForm(data=request.POST, files=request.FILES)
        project_id = kwargs["pk"]
        project = UserFile.objects.get(id__iexact=project_id)

        if files_form.is_valid():
            name = files_form.cleaned_data.get('name')
            thema = files_form.cleaned_data.get('thema')
            end_date = files_form.cleaned_data.get('end_date')
            now = timezone.now()
            upload_date = moment.utcnow().timezone(
                'Europe/Brussels')  # same as today but used for calculations
            checker_end_date = moment.date(end_date)
            delta_deadline = (checker_end_date - upload_date).days
            project_file = files_form.cleaned_data.get('file')

            # remove the file first
            project.file.delete()
            project.save()

            # update all but the word count and price
            project.name = name
            project.thema = thema
            project.upload_date = now
            project.file = project_file
            project.end_date = end_date
            project.save()

            # update the word count and price
            path = project.file.path
            helper = HelperFunctions(path)
            word_count = helper.get_word_count()
            price = helper.calculate_price(delta_deadline, word_count)

            project.word_count = word_count
            project.price = price
            project.save()

            return redirect('dashboard')

        return render(request, 'dashboard/project_edit.html',
                      {'files_form': files_form})
Beispiel #23
0
    def post(request):
        files_form = CreateUserFileForm(data=request.POST, files=request.FILES)

        if files_form.is_valid():
            name = files_form.cleaned_data.get('name')
            thema = files_form.cleaned_data.get('thema')
            end_date = files_form.cleaned_data.get('end_date')
            owner = request.user
            now = timezone.now()
            upload_date = moment.utcnow().timezone(
                'Europe/Brussels')  # same as today but used for calculations
            checker_end_date = moment.date(end_date)
            delta_deadline = (checker_end_date - upload_date).days
            project_file = files_form.cleaned_data.get('file')

            if not UserFile.objects.filter(name=name).exists():
                project = UserFile.objects.create(owner=owner,
                                                  name=name,
                                                  thema=thema,
                                                  upload_date=now,
                                                  end_date=end_date,
                                                  file=project_file)
                path = project.file.path
                helper = HelperFunctions(path)
                word_count = helper.get_word_count()
                price = helper.calculate_price(delta_deadline, word_count)

                project.word_count = word_count
                project.price = price
                project.save()
                return redirect('dashboard')
            else:
                # vervang dit later door ajax
                return render(
                    request, 'dashboard/project_new.html', {
                        'files_form': files_form,
                        'bestaat': 'deze opdracht bestaat al reeds',
                    })

        return render(request, 'dashboard/project_new.html',
                      {'files_form': files_form})
Beispiel #24
0
    def insert_one(mongo_db, type_, id_):
        if type_ not in Device.ALLOWED_TYPES:
            return {'status': 'error', 'mensaje': 'Tipo de dispositivo no permitido.'}

        if type_ == 'email' and not validate_email(id_):
            return {'status': 'error', 'mensaje': 'Email inválido'}

        row = mongo_db.devices.find_one({'tipo': type_, 'id': id_})
        if row is None:
            data = {
                'tipo': type_,
                'id': id_,
                'fecha_registro': moment.utcnow().timezone(CONFIG['moment']['timezone']).isoformat()
            }
            mongo_db.devices.insert_one(data)
        else:
            data = row

        if '_id' in data:
            del data['_id']

        return {'status': 'ok', 'data': data}
def reset_password(params):
	if not("code" in params and "password" in params and "confirm" in params):
		raise WebException("Please fill out all the fields.")
	
	if params["password"] != params["confirm"]:
		raise WebException("Your passwords don't match, silly!")
	
	db = api.common.db_conn()
	
	ticket = db.password_recovery.find_one({ "code": params["code"], "active": True })
	if ticket is None:
		raise WebException("That code doesn't seem to be right.")
	
	now = moment.utcnow().date.timestamp()
	expiredate = moment.unix(ticket["expire"], utc=True).date.timestamp()
	if now > expiredate:
		raise WebException("Your code expired!")
	
	db.password_recovery.update_one({ "code": params["code"], "active": True }, { "$set": { "active": False } })
	phash = hash_password(params["password"])
	db.users.update_one({ "email": ticket["email"].lower() }, { "$set": { "password": phash } })
	
	return
		elif opt in (u"-p", u"--port"):
			port = arg
#		elif opt in ("-w", "--pwd"):
#			pwd = arg

	exitapp = [ False ]
	q = Queue.Queue()
	mdr = musicdata_volumio2(q, server, port, exitapp)

	try:
		while True:
			try:
				status = q.get(timeout=1000)
				q.task_done()

				ctime = moment.utcnow().timezone(u"US/Eastern").strftime(u"%-I:%M:%S %p").strip()
				print u"\n\nStatus at time {0}".format(ctime)
				for item,value in status.iteritems():
					print u"    [{0}]={1} {2}".format(item,value, type(value))
				print u"\n\n"

			except Queue.Empty:
				pass
	except KeyboardInterrupt:
		print ''
		pass
	finally:
		exitapp[0] = True

	print u"Exiting..."
	def status(self):

		# If you are using Rune
		if RUNE_ENABLED:
			status = self.status_redis()
		elif MPD_ENABLED or SPOP_ENABLED or LMS_ENABLED:

			if MPD_ENABLED:
				# Try MPD daemon
				status = self.status_mpd()
			else:
				status = { 'state':u"stop", 'artist':u"", 'title':u"", 'album':u"", 'remaining':u"", 'current':0, 'duration':0, 'position':u"", 'volume':0, 'playlist_display':u"", 'playlist_position':0, 'playlist_count':0, 'bitrate':u"", 'type':u"" }

			# If MPD is stopped
			if status.get('state') != "play":

				# Try SPOP
				if SPOP_ENABLED:
					status = self.status_spop()
				else:
					status = { 'state':u"stop", 'artist':u"", 'title':u"", 'album':u"", 'remaining':u"", 'current':0, 'duration':0, 'position':u"", 'volume':0, 'playlist_display':u"", 'playlist_position':0, 'playlist_count':0, 'bitrate':u"", 'type':u""}

				# If SPOP is stopped
				if status.get('state') != "play":

					# Try LMS
					if LMS_ENABLED:
						status = self.status_lms()
					else:
						status = { 'state':u"stop", 'artist':u"", 'title':u"", 'album':u"", 'remaining':u"", 'current':0, 'duration':0, 'position':u"", 'volume':0, 'playlist_display':u"", 'playlist_position':0, 'playlist_count':0, 'bitrate':u"", 'type':u""}
		else:
			status = { 'state':u"stop", 'artist':u"", 'title':u"", 'album':u"", 'remaining':u"", 'current':0, 'duration':0, 'position':u"", 'volume':0, 'playlist_display':u"", 'playlist_position':0, 'playlist_count':0, 'bitrate':u"", 'type':u""}


		# Add system variables

		try:
			if TIME24HOUR == True:
				current_time = moment.utcnow().timezone(TIMEZONE).strftime("%H:%M").strip()
				current_time_sec = moment.utcnow().timezone(TIMEZONE).strftime("%H:%M:%S").strip()
			else:
				current_time = moment.utcnow().timezone(TIMEZONE).strftime("%-I:%M %p").strip()
				current_time_sec = moment.utcnow().timezone(TIMEZONE).strftime("%-I:%M:%S %p").strip()
		except ValueError:
			# Don't know why but on exit, the moment code is occasionally throwing a ValueError
			current_time = "00:00"
			current_time_sec = "00:00:00"

		current_ip = commands.getoutput("ip -4 route get 1 | head -1 | cut -d' ' -f8 | tr -d '\n'").strip()


		# Read Temperature from Pi's on-board temperature sensor once every 20 seconds
		if self.tempreadexpired < time.time():
			self.tempreadexpired = time.time()+20
			try:
				file = open("/sys/class/thermal/thermal_zone0/temp")
				self.tempc = int(file.read())

				# Convert value to float and correct decimal place
				self.tempc = round(float(self.tempc) / 1000,1)

				# convert to fahrenheit
				self.tempf = round(self.tempc*9/5+32,1)

				file.close()
			except IOError:
				self.tempc = 0.0
				self.tempf = 0.0
			except AttributeError:
				file.close()
				self.tempc = 0.0
				self.tempf = 0.0

		# Read available disk space remaining every 20 seconds
		if self.diskreadexpired < time.time():
			self.diskreadexpired = time.time() + 20
			try:
				# Check if running on OSX.  If yes, adjust df command
				if sys.platform == "darwin":
					p = os.popen("df /")
					line = p.readline()
					line = p.readline()
					va = line.split()
					line = "{0} {1}".format(va[3], va[4])
				else:
					# assume running on Raspberry linux
					p = os.popen("df --output='avail','pcent' /")
					line = p.readline()
					line = p.readline().strip()

				va = line.split()
				self.avail = va[0]
				self.availp = va[1]

				# remove % sign
				self.availp = self.availp[0:len(self.availp)-1]

				self.avail = int(self.avail)
				self.availp = int(self.availp)

				p.close()
			except IOError:
				self.avail = 0
				self.availp = 0
			except AttributeError:
				p.close()
				self.avail = 0
				self.availp = 0


		status['current_tempc'] = self.tempc
		status['current_tempf'] = self.tempf
		status['disk_avail'] = self.avail
		status['disk_availp'] = self.availp
		status['current_time'] = current_time
		status['current_time_sec'] = current_time
		status['current_ip'] = current_ip

		# if logging of the status data has been requested record the current status
		if STATUSLOGGING:
			self.statusfile.write(str(status)+'\n')
			self.statusfile.flush()

		return status
Beispiel #28
0
    def updatesystemvars(self):
        while True:
            try:
                utc = moment.utcnow()
                localtime = moment.utcnow().timezone(pydPiper_config.TIMEZONE)
                current_time_ampm = moment.utcnow().timezone(
                    pydPiper_config.TIMEZONE).strftime(u"%p").strip().decode()
                if pydPiper_config.TIME24HOUR == True:
                    current_time = moment.utcnow().timezone(
                        pydPiper_config.TIMEZONE).strftime(
                            u"%H:%M").strip().decode()
                    current_time_sec = moment.utcnow().timezone(
                        pydPiper_config.TIMEZONE).strftime(
                            u"%H:%M:%S").strip().decode()
                else:
                    current_time = moment.utcnow().timezone(
                        pydPiper_config.TIMEZONE).strftime(
                            u"%-I:%M %p").strip().decode()
                    current_time_sec = moment.utcnow().timezone(
                        pydPiper_config.TIMEZONE).strftime(
                            u"%-I:%M:%S %p").strip().decode()
            except ValueError:
                # Don't know why but on exit, the moment code is occasionally throwing a ValueError
                current_time = u"00:00"
                current_time_sec = u"00:00:00"
                current_time_ampm = u''
                utc = None
                localtime = None

            current_ip = commands.getoutput(
                u"ip -4 route get 1 | head -1 | cut -d' ' -f8 | tr -d '\n'"
            ).strip()

            outside_tempf = 0.0
            outside_tempc = 0.0
            outside_temp = 0.0
            outside_temp_max = 0.0
            outside_temp_min = 0.0
            outside_conditions = u'No data'
            outside_temp_formatted = u'0'
            outside_temp_max_formatted = u'0'
            outside_temp_min_formatted = u'0'

            #

            try:
                wq = 'http://api.wunderground.com/api/' + pydPiper_config.WUNDER_API + '/geolookup/conditions/forecast/q/' + pydPiper_config.WUNDER_LOCATION + '.json'
                response = urllib2.urlopen(wq)
                json_result = response.read()

                try:
                    parsed_json = json.loads(json_result)

                    location = parsed_json['location']['city']
                    outside_tempf = parsed_json['current_observation'][
                        'temp_f']
                    outside_tempc = parsed_json['current_observation'][
                        'temp_c']
                    outside_temp_maxf = float(
                        parsed_json['forecast']['simpleforecast']
                        ['forecastday'][0]['high']['fahrenheit'])
                    outside_temp_maxc = float(
                        parsed_json['forecast']['simpleforecast']
                        ['forecastday'][0]['high']['celsius'])
                    outside_temp_minf = float(
                        parsed_json['forecast']['simpleforecast']
                        ['forecastday'][0]['low']['fahrenheit'])
                    outside_temp_minc = float(
                        parsed_json['forecast']['simpleforecast']
                        ['forecastday'][0]['low']['celsius'])
                    outside_conditions = parsed_json['current_observation'][
                        'weather']

                    if pydPiper_config.TEMPERATURE.lower() == u'celsius':
                        outside_temp = outside_tempc
                        outside_temp_max = int(outside_temp_maxc)
                        outside_temp_min = int(outside_temp_minc)
                        outside_temp_formatted = u"{0}°C".format(
                            int(outside_temp))
                        outside_temp_max_formatted = u"{0}°C".format(
                            int(outside_temp_max))
                        outside_temp_min_formatted = u"{0}°C".format(
                            int(outside_temp_min))
                    else:
                        outside_temp = outside_tempf
                        outside_temp_max = int(outside_temp_maxf)
                        outside_temp_min = int(outside_temp_minf)
                        outside_temp_formatted = u"{0}°F".format(
                            int(outside_temp))
                        outside_temp_max_formatted = u"{0}°F".format(
                            int(outside_temp_max))
                        outside_temp_min_formatted = u"{0}°F".format(
                            int(outside_temp_min))

                except ValueError:
                    logging.warning(
                        'Failed to decode result from Weather Underground Query.  Query string was {0}.  Response was {1}'
                        .format(wq, json_result))

            except urllib2.HTTPError as e:
                logging.warning(
                    'The Weather Underground server couldn\'t fulfill the request and responded with error code {0}'
                    .format(e.code))
            except urllib2.URLError as e:
                logging.warning(
                    'Could not reach the Weather Underground server.  Reason provided was {0}'
                    .format(e.reason))
            except (AttributeError, KeyError):
                logging.warning(
                    'Weather Underground API key or location are missing from configuration file'
                )

            # try:
            # owm = pyowm.OWM(pydPiper_config.OWM_API)
            # obs = owm.weather_at_coords(pydPiper_config.OWM_LAT, pydPiper_config.OWM_LON)
            # fc = owm.daily_forecast_at_coords(pydPiper_config.OWM_LAT, pydPiper_config.OWM_LON)
            # f = fc.get_forecast()
            # dailyfc = f.get_weathers()
            # wea = obs.get_weather()
            #
            # outside_tempf = wea.get_temperature(u'fahrenheit')[u'temp']
            # outside_temp_maxf = dailyfc[0].get_temperature(u'fahrenheit')[u'max']
            # outside_temp_minf = dailyfc[0].get_temperature(u'fahrenheit')[u'min']
            #
            # outside_tempc = wea.get_temperature(u'celsius')[u'temp']
            # outside_temp_maxc = dailyfc[0].get_temperature(u'celsius')[u'max']
            # outside_temp_minc = dailyfc[0].get_temperature(u'celsius')[u'min']
            #
            # # Localize temperature value
            # if pydPiper_config.TEMPERATURE.lower() == u'celsius':
            # 	outside_temp = outside_tempc
            # 	outside_temp_max = int(outside_temp_maxc)
            # 	outside_temp_min = int(outside_temp_minc)
            # 	outside_temp_formatted = u"{0}°C".format(int(outside_temp))
            # 	outside_temp_max_formatted = u"{0}°C".format(int(outside_temp_max))
            # 	outside_temp_min_formatted = u"{0}°C".format(int(outside_temp_min))
            # else:
            # 	outside_temp = outside_tempf
            # 	outside_temp_max = int(outside_temp_maxf)
            # 	outside_temp_min = int(outside_temp_minf)
            # 	outside_temp_formatted = u"{0}°F".format(int(outside_temp))
            # 	outside_temp_max_formatted = u"{0}°F".format(int(outside_temp_max))
            # 	outside_temp_min_formatted = u"{0}°F".format(int(outside_temp_min))
            #
            # outside_conditions = wea.get_detailed_status()
            # except:
            # 	logging.debug(u"Failed to get weather data.  Check OWM_API key.")
            # 	pass

            try:
                with open(u"/sys/class/thermal/thermal_zone0/temp") as file:
                    system_tempc = int(file.read())

                # Convert value to float and correct decimal place
                system_tempc = round(float(system_tempc) / 1000, 1)

                # convert to fahrenheit
                system_tempf = round(system_tempc * 9 / 5 + 32, 1)

            except AttributeError:
                system_tempc = 0.0
                system_tempf = 0.0

            try:
                if pydPiper_config.TEMPERATURE.lower() == u'celsius':
                    system_temp = system_tempc
                    system_temp_formatted = u"{0}°c".format(int(system_temp))
                else:
                    system_temp = system_tempf
                    system_temp_formatted = u"{0}°f".format(int(system_temp))
            except:
                system_temp = system_tempf
                system_temp_formatted = u"{0}°f".format(int(system_temp))

            try:
                # Check if running on OSX.  If yes, adjust df command
                if sys.platform == u"darwin":
                    with os.popen(u"df /") as p:
                        p = os.popen(u"df /")
                        line = p.readline()
                        line = p.readline()

                    va = line.split()
                    line = "{0} {1}".format(va[3], va[4])
                else:
                    # assume running on Raspberry linux
                    with os.popen(u"df -B 1 /") as p:
                        line = p.readline()
                        line = p.readline().strip()

                va = line.split()
                avail = int(va[3])
                usedp = int(va[4][:-1])  # Remove trailing % and convert to int
                used = int(va[2])
                availp = 100 - usedp

            except AttributeError:
                avail = 0
                availp = 0
                usedp = 0
                used = 0

            with self.musicdata_lock:
                self.musicdata[u'system_temp'] = system_temp
                self.musicdata[
                    u'system_temp_formatted'] = system_temp_formatted

                self.musicdata[u'system_tempc'] = system_tempc
                self.musicdata[u'system_tempf'] = system_tempf

                # For backward compatibility
                self.musicdata[u'current_tempc'] = self.musicdata[
                    u'system_tempc']
                self.musicdata[u'current_tempf'] = self.musicdata[
                    u'system_tempf']

                self.musicdata[u'disk_avail'] = avail
                self.musicdata[u'disk_availp'] = availp
                self.musicdata[u'disk_used'] = used
                self.musicdata[u'disk_usedp'] = usedp

                self.musicdata[u'utc'] = utc
                self.musicdata[u'localtime'] = localtime
                self.musicdata[u'time'] = current_time
                self.musicdata[u'time_ampm'] = current_time_ampm
                # note: 'time_formatted' is computed during page processing as it needs the value of the strftime key contained on the line being displayed

                # For backwards compatibility
                self.musicdata[u'current_time'] = current_time
                self.musicdata[u'current_time_sec'] = current_time

                self.musicdata[u'ip'] = current_ip.decode()

                # For backwards compatibility
                self.musicdata[u'current_ip'] = current_ip.decode()

                self.musicdata[u'outside_temp'] = outside_temp
                self.musicdata[u'outside_temp_max'] = outside_temp_max
                self.musicdata[u'outside_temp_min'] = outside_temp_min
                self.musicdata[
                    u'outside_temp_formatted'] = outside_temp_formatted
                self.musicdata[
                    u'outside_temp_max_formatted'] = outside_temp_max_formatted
                self.musicdata[
                    u'outside_temp_min_formatted'] = outside_temp_min_formatted
                self.musicdata[u'outside_conditions'] = outside_conditions

            # Read environmentals every 5 minutes
            time.sleep(300)
		currentArtist = ""
		currentTitle = ""
		cpos = ""

		ctime = ""
		hesitate = False
		hesitation_etime = 0
		display_etime = 0
		notplaying_state = "TIME"
		ctime = ""
		hesitation_etime = time.time() + HESITATION_TIME


		while True:
			if TIME24HOUR == True:
				current_time = moment.utcnow().timezone(TIMEZONE).format("HH:mm").strip()
			else:
				current_time = moment.utcnow().timezone(TIMEZONE).format("h:m a").strip()
				
			current_ip = commands.getoutput("ip -4 route get 1 | head -1 | cut -d' ' -f8 | tr -d '\n'").strip()

			cstatus = rd.status()
			state = cstatus.get('state')

			if state != "play":
				if beenplaying:
					beenplaying = False
					currentArtist = ""
					currentTitle = ""
					notplaying_state = "TIME"
					hesitation_etime = time.time() + NOTPLAYING_TIMEDISPLAY
Beispiel #30
0
        elif opt in (u"-p", u"--port"):
            port = arg
#		elif opt in ("-w", "--pwd"):
#			pwd = arg

    exitapp = [False]
    q = Queue.Queue()
    mdr = musicdata_volumio2(q, server, port, exitapp)

    try:
        while True:
            try:
                status = q.get(timeout=1000)
                q.task_done()

                ctime = moment.utcnow().timezone(u"US/Eastern").strftime(
                    u"%-I:%M:%S %p").strip()
                print u"\n\nStatus at time {0}".format(ctime)
                for item, value in status.iteritems():
                    print u"    [{0}]={1} {2}".format(item, value, type(value))
                print u"\n\n"

            except Queue.Empty:
                pass
    except KeyboardInterrupt:
        print ''
        pass
    finally:
        exitapp[0] = True

    print u"Exiting..."
Beispiel #31
0
    def parse(self):
        reports = {'restriction': [], 'air_quality': []}

        if self.url.startswith('file://'):
            document = pq(filename=self.url.replace('file://', ''))
        else:
            document = pq(url=self.url)

        current_year = moment.utcnow().timezone(CONFIG['moment']['timezone']).format('YYYY')
        rows = document('.selecthistory #table-%s tbody tr' % current_year)

        for row in rows[2:]:
            date_ = moment.date(row.find('td[3]').text.strip(), '%d-%m-%Y').format('YYYY-M-D')
            reports['air_quality'].append(AirQualityReport.dict(
                UOCT_Crawler.url,
                {
                    'ciudad': 'Santiago',
                    'fecha': date_,
                    'estado': row.find('td[1]').text.strip()
                }
            ))

            reports['restriction'].append(RestrictionReport.dict(
                UOCT_Crawler.url,
                {
                    'ciudad': 'Santiago',
                    'fecha': date_,
                    'sin_sello_verde': self.clean_digits_string(row.find('td[4]').text),
                    'con_sello_verde': self.clean_digits_string(row.find('td[5]').text),
                }
            ))

        reports['restriction'].sort(key=lambda r: r['fecha'], reverse=True)

        # Current day info
        info = document('.eventslist .restriction h3')
        if len(info) != 2:
            return reports

        date_ = moment.utcnow().timezone(CONFIG['moment']['timezone']).format('YYYY-M-D')

        air_quality_report = AirQualityReport.dict(
            UOCT_Crawler.url,
            {
                'ciudad': 'Santiago',
                'fecha': date_,
                'estado': 'Normal'
            }
        )
        self.insert_report_in_position(reports['air_quality'], air_quality_report)

        restriction_report = RestrictionReport.dict(
            UOCT_Crawler.url,
            {
                'ciudad': 'Santiago',
                'fecha': date_,
                'sin_sello_verde': self.clean_digits_string(info[0].text),
                'con_sello_verde': self.clean_digits_string(info[1].text),
            }
        )
        self.insert_report_in_position(reports['restriction'], restriction_report)

        return reports
Beispiel #32
0
    def demo(self):

        db = {
                'actPlayer':'mpd',
                'playlist_position':1,
                'playlist_length':5,
                 'title':"Nicotine & Gravy",
                'artist':"Beck",
                'album':'Midnight Vultures',
                'elapsed':0,
                'length':400,
                'volume':50,
                'stream':'Not webradio',
                'utc':     moment.utcnow(),
                'outside_temp_formatted':'46\xb0F',
                'outside_temp_max':72,
                'outside_temp_min':48,
                'outside_conditions':'Windy',
                'system_temp_formatted':'98\xb0C',
                'state':'stop',
                'system_tempc':81.0
            }

        dbp = {
                'actPlayer':'mpd',
                'playlist_position':1,
                'playlist_length':5,
                 'title':"Nicotine & Gravy",
                'artist':"Beck",
                'album':'Midnight Vultures',
                'elapsed':0,
                'length':400,
                'volume':50,
                'stream':'Not webradio',
                'utc': moment.utcnow(),
                'outside_temp_formatted':'46\xb0F',
                'outside_temp_max':72,
                'outside_temp_min':48,
                'outside_conditions':'Windy',
                'system_temp_formatted':'98\xb0C',
                'state':'stop',
                'system_tempc':81.0
            }

        events = [
            (15, 'state', 'play'),
            (20, 'title', 'Mixed Bizness'),
            (30, 'volume', 80),
            (40, 'title', 'I Never Loved a Man (The Way I Love You)'),
            (40, 'artist', 'Aretha Franklin'),
            (40, 'album', 'The Queen Of Soul'),
            (70, 'state', 'stop'),
            (90, 'state', 'play'),
            (100, 'title', 'Do Right Woman, Do Right Man'),
            (120, 'volume', 100),
            (140, 'state', 'play' )
        ]

        starttime = time.time()
        elapsed = int(time.time()-starttime)
        timepos = time.strftime(u"%-M:%S", time.gmtime(int(elapsed))) + "/" + time.strftime(u"%-M:%S", time.gmtime(int(254)))

        dc = display.display_controller((80,16))
        f_path = os.path.join(os.path.dirname(__file__), 'pages_test.py')
        dc.load(f_path, db,dbp )

        starttime=time.time()
        while True:
            elapsed = int(time.time()-starttime)
            db['elapsed']=elapsed
            db['utc'] = moment.utcnow()
            self.processevent(events, starttime, 'pre', db, dbp)
            img = dc.next()
            self.processevent(events, starttime, 'post', db, dbp)
            lcd.update(img)
            time.sleep(.01)
class music_controller(threading.Thread):
	# Receives updates from music services
	# Determines what page to displays
	# Sends relevant updates to display_controller

	# musicdata variables.
	# Includes all from musicdata class plus environmentals
	musicdata_init = {
		'state':u"stop",
		'musicdatasource':u"",
		'actPlayer':u"",
		'artist':u"",
		'title':u"",
		'album':u"",
		'uri':u"",
		'current':-1,
		'elapsed':-1,
		'remaining':u"",
		'total_time':u"",
		'duration':-1,
		'length':-1,
		'position':u"",
		'elapsed_formatted':u"",
		'elapsed_simple':u"",
		'volume':-1,
		'repeat': 0,
		'single': 0,
		'random': 0,
		'channels':0,
		'bitdepth':u"",
		'bitrate':u"",
		'samplerate':u"",
		'type':u"",
		'tracktype':u"",
		'repeat_onoff': u"Off",
		'single_onoff': u"Off",
		'random_onoff': u"Off",
		'playlist_display':u"",
		'playlist_position':-1,
		'playlist_count':-1,
		'playlist_length':-1,
		'current_tempc':0,
		'current_tempf':0,
		'disk_avail':0,
		'disk_availp':0,
		'current_time':u"",
		'utc':moment.utcnow(),
		'localtime':moment.utcnow().timezone(pydPiper_config.TIMEZONE),
		'current_time_sec':u"",
		'current_time_formatted':u"",
		'current_ip':u"",
		'outside_conditions':'No Data',
		'outside_temp_min':0,
		'outside_temp_max':0,
		'outside_temp_formatted':'',
		'system_temp_formatted':''
	}


	def __init__(self, servicelist, display_controller, showupdates=False):
		threading.Thread.__init__(self)

		self.daemon = True
		self.musicqueue = Queue.Queue()
		self.image = None
		self.showupdates = showupdates
		self.display_controller = display_controller

		self.musicdata = copy.deepcopy(self.musicdata_init)
		self.musicdata_prev = copy.deepcopy(self.musicdata)
		self.servicelist = servicelist
		self.services = { }

		# Attempt to initialize services
		self.initservices()

		# Lock used to prevent simultaneous update of the musicdata dictionary
		self.musicdata_lock = threading.Lock()


	def initservices(self):

		# Make sure that if rune is selected that is is the only service that is selected
		if u"rune" in self.servicelist and len(self.servicelist) > 1:
			logging.critical(u"Rune service can only be used alone")
			raise RuntimeError(u"Rune service can only be used alone")
		if u"volumio" in self.servicelist and len(self.servicelist) > 1:
			logging.critical(u"Volumio service can only be used alone")
			raise RuntimeError(u"Volumio service can only be used alone")

		musicservice = None
		for s in self.servicelist:
			s = s.lower()
			try:
				if s == u"mpd":
					musicservice = sources.musicdata_mpd.musicdata_mpd(self.musicqueue, pydPiper_config.MPD_SERVER, pydPiper_config.MPD_PORT, pydPiper_config.MPD_PASSWORD)
				elif s == u"spop":
					musicservice = sources.musicdata_spop.musicdata_spop(self.musicqueue, pydPiper_config.SPOP_SERVER, pydPiper_config.SPOP_PORT, pydPiper_config.SPOP_PASSWORD)
				elif s == u"lms":
					musicservice = sources.musicdata_lms.musicdata_lms(self.musicqueue, pydPiper_config.LMS_SERVER, pydPiper_config.LMS_PORT, pydPiper_config.LMS_USER, pydPiper_config.LMS_PASSWORD, pydPiper_config.LMS_PLAYER)
				elif s == u"rune":
					musicservice = sources.musicdata_rune.musicdata_rune(self.musicqueue, pydPiper_config.RUNE_SERVER, pydPiper_config.RUNE_PORT, pydPiper_config.RUNE_PASSWORD)
				elif s == u"volumio":
					musicservice = sources.musicdata_volumio2.musicdata_volumio2(self.musicqueue, pydPiper_config.VOLUMIO_SERVER, pydPiper_config.VOLUMIO_PORT, exitapp )
				else:
					logging.debug(u"Unsupported music service {0} requested".format(s))
					continue
			except NameError:
				# Missing dependency for requested servicelist
				logging.warning(u"Request for {0} failed due to missing dependencies".format(s))
				pass
			if musicservice != None:
				self.services[s] = musicservice

		if len(self.services) == 0:
			logging.critical(u"No music services succeeded in initializing")
			raise RuntimeError(u"No music services succeeded in initializing")

	def run(self):

		logging.debug(u"Music Controller Starting")

		# Start the thread that updates the system variables
		sv_t = threading.Thread(target=self.updatesystemvars)
		sv_t.daemon = True
		sv_t.start()
		timesongstarted = 0


		# Inform the system that we are starting up
		with self.musicdata_lock:
			self.musicdata_prev[u'state'] = ''
			self.musicdata[u'state'] = 'starting'
		self.starttime = time.time()

		lastupdate = 0 # Initialize variable to be used to force updates every second regardless of the receipt of a source update
		while not exitapp[0]:

			updates = { }

			# Check if we are starting up.  If yes, update pages to display any start message.
			if self.starttime + pydPiper_config.STARTUP_MSG_DURATION > time.time():
				time.sleep(pydPiper_config.STARTUP_MSG_DURATION)
				with self.musicdata_lock:
					self.musicdata['state'] = 'stop'
				continue

			# Attempt to get an update from the queue
			try:
				updates = self.musicqueue.get_nowait()
				self.musicqueue.task_done()
			except Queue.Empty:
				pass

			# Get current time
			try:
				utc = moment.utcnow()
				localtime = moment.utcnow().timezone(pydPiper_config.TIMEZONE)
				current_time_ampm = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%p").strip().decode()
				if pydPiper_config.TIME24HOUR == True:
					current_time = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%H:%M").strip().decode()
					current_time_sec = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%H:%M:%S").strip().decode()
				else:
					current_time = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%-I:%M %p").strip().decode()
					current_time_sec = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%-I:%M:%S %p").strip().decode()
			except ValueError:
				# Don't know why but on exit, the moment code is occasionally throwing a ValueError
				current_time = u"00:00"
				current_time_sec = u"00:00:00"
				current_time_ampm = u''
				utc = None
				localtime = None

			with self.musicdata_lock:
				# Update musicdata based upon received message
				for item, value in updates.iteritems():
					self.musicdata[item] = value

				# Update song timing variables
				if u'elapsed' in updates:
					self.musicdata[u'elapsed'] = self.musicdata[u'current'] = updates[u'elapsed']
					timesongstarted = time.time() - self.musicdata[u'elapsed']


				if self.musicdata[u'state'] == u'play':
					if u'elapsed' not in updates:
						if timesongstarted > 0:
							self.musicdata[u'elapsed'] = int(time.time() - timesongstarted)
						else:
							# We got here without timesongstarted being set which is a problem...
							logging.debug(u"Trying to update current song position with an uninitialized start time")

				# If the value of current has changed then update the other related timing variables
				if self.musicdata[u'elapsed'] != self.musicdata_prev[u'elapsed']:
					timepos = time.strftime("%-M:%S", time.gmtime(self.musicdata[u'elapsed']))
					timepos_advanced = timepos
					total_time = "00:00"
					if self.musicdata[u'length'] > 0:						
						timepos_advanced = time.strftime("%-M:%S", time.gmtime(self.musicdata[u'elapsed'])) + "/" + time.strftime("%-M:%S", time.gmtime(self.musicdata[u'length']))
						remaining = time.strftime("%-M:%S", time.gmtime(self.musicdata[u'length'] - self.musicdata[u'elapsed']))
						total_time = time.strftime("%-M:%S", time.gmtime(self.musicdata[u'length']))
					else:						
						remaining = timepos

					self.musicdata[u'elapsed_formatted'] = timepos_advanced.decode()
					self.musicdata[u'remaining'] = remaining.decode()
					self.musicdata[u'elapsed_simple'] = self.musicdata[u'position'] = timepos.decode()
					self.musicdata[u'total_time'] = total_time.decode()

				# Update onoff variables (random, single, repeat)
				self.musicdata[u'random_onoff'] = u"On" if self.musicdata[u'random'] else u"Off"
				self.musicdata[u'single_onoff'] = u"On" if self.musicdata[u'single'] else u"Off"
				self.musicdata[u'repeat_onoff'] = u"On" if self.musicdata[u'repeat'] else u"Off"

				# update time variables
				self.musicdata[u'utc'] = utc
				self.musicdata[u'localtime'] = localtime
				self.musicdata[u'time'] = current_time
				self.musicdata[u'time_ampm'] = current_time_ampm
				# note: 'time_formatted' is computed during page processing as it needs the value of the strftime key contained on the line being displayed

				# For backwards compatibility
				self.musicdata[u'current_time'] = current_time
				self.musicdata[u'current_time_sec'] = current_time


			# If anything has changed, update pages ### probably unnecessary to check this now that time is being updated in this section
			if self.musicdata != self.musicdata_prev or lastupdate < time.time():

				# Set lastupdate time to 1 second in the future
				lastupdate = time.time()+1

				self.musicdata[u'time_formatted'] = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime('%H:%M').strip().decode()
				# To support previous key used for this purpose
				self.musicdata[u'current_time_formatted'] = self.musicdata[u'time_formatted']

				# Update display controller
				# The primary call to this routine is in main but this call is needed to catch variable changes before musicdata_prev is updated.
				self.display_controller.next()

				# Print the current contents of musicdata if showupdates is True
				if self.showupdates:

					# Check to see if a variable has changed (except time variables)
					shouldshowupdate = False
					for item, value in self.musicdata.iteritems():
						try:
							if item in ['utc', 'localtime', 'time', 'time_ampm', 'current_time', 'current_time_sec']:
								continue
							if self.musicdata_prev[item] != value:
								shouldshowupdate = True
								break
						except KeyError:
							shouldshowupdate = True
							break


					if shouldshowupdate:
						ctime = localtime.strftime("%-I:%M:%S %p").strip()
						print u"Status at time {0}".format(ctime)

						with self.musicdata_lock:
							for item,value in self.musicdata.iteritems():
								try:
									print u"    [{0}]={1} {2}".format(item,repr(value), type(value))
								except:
									print u"err"
									print u"[{0}] =".format(item)
									print type(value)
									print repr(value)
							print u"\n"

				# Update musicdata_prev
				with self.musicdata_lock:
					for item, value in self.musicdata.iteritems():
						try:
							if self.musicdata_prev[item] != value:
								self.musicdata_prev[item] = value
						except KeyError:
							self.musicdata_prev[item] = value

			# Update display data every 1/4 second
			time.sleep(.25)


	def updatesystemvars(self):
		while True:

			current_ip = commands.getoutput(u"ip -4 route get 1 | head -1 | cut -d' ' -f8 | tr -d '\n'").strip()

			outside_tempf = 0.0
			outside_tempc = 0.0
			outside_temp = 0.0
			outside_temp_max = 0.0
			outside_temp_min = 0.0
			outside_conditions = u'No data'
			outside_temp_formatted = u'0'
			outside_temp_max_formatted = u'0'
			outside_temp_min_formatted = u'0'

#

			try:
				wq = 'http://api.wunderground.com/api/' + pydPiper_config.WUNDER_API + '/geolookup/conditions/forecast/q/' + pydPiper_config.WUNDER_LOCATION + '.json'
				response = urllib2.urlopen(wq)
				json_result = response.read()

				try:
					parsed_json = json.loads(json_result)

					location = parsed_json['location']['city']
					outside_tempf = parsed_json['current_observation']['temp_f']
					outside_tempc = parsed_json['current_observation']['temp_c']
					outside_temp_maxf = float(parsed_json['forecast']['simpleforecast']['forecastday'][0]['high']['fahrenheit'])
					outside_temp_maxc = float(parsed_json['forecast']['simpleforecast']['forecastday'][0]['high']['celsius'])
					outside_temp_minf = float(parsed_json['forecast']['simpleforecast']['forecastday'][0]['low']['fahrenheit'])
					outside_temp_minc = float(parsed_json['forecast']['simpleforecast']['forecastday'][0]['low']['celsius'])
					outside_conditions = parsed_json['current_observation']['weather']

					if pydPiper_config.TEMPERATURE.lower() == u'celsius':
						outside_temp = outside_tempc
						outside_temp_max = int(outside_temp_maxc)
						outside_temp_min = int(outside_temp_minc)
						outside_temp_formatted = u"{0}°C".format(int(outside_temp))
						outside_temp_max_formatted = u"{0}°C".format(int(outside_temp_max))
						outside_temp_min_formatted = u"{0}°C".format(int(outside_temp_min))
					else:
						outside_temp = outside_tempf
						outside_temp_max = int(outside_temp_maxf)
						outside_temp_min = int(outside_temp_minf)
						outside_temp_formatted = u"{0}°F".format(int(outside_temp))
						outside_temp_max_formatted = u"{0}°F".format(int(outside_temp_max))
						outside_temp_min_formatted = u"{0}°F".format(int(outside_temp_min))

				except ValueError:
					logging.warning('Failed to decode result from Weather Underground Query.  Query string was {0}.  Response was {1}'.format(wq,json_result))

			except urllib2.HTTPError as e:
				logging.warning('The Weather Underground server couldn\'t fulfill the request and responded with error code {0}'.format(e.code))
			except urllib2.URLError as e:
				logging.warning('Could not reach the Weather Underground server.  Reason provided was {0}'.format(e.reason))
			except (AttributeError, KeyError):
				logging.warning('Weather Underground API key or location are missing from configuration file')




			# try:
				# owm = pyowm.OWM(pydPiper_config.OWM_API)
				# obs = owm.weather_at_coords(pydPiper_config.OWM_LAT, pydPiper_config.OWM_LON)
				# fc = owm.daily_forecast_at_coords(pydPiper_config.OWM_LAT, pydPiper_config.OWM_LON)
				# f = fc.get_forecast()
				# dailyfc = f.get_weathers()
				# wea = obs.get_weather()
				#
				# outside_tempf = wea.get_temperature(u'fahrenheit')[u'temp']
				# outside_temp_maxf = dailyfc[0].get_temperature(u'fahrenheit')[u'max']
				# outside_temp_minf = dailyfc[0].get_temperature(u'fahrenheit')[u'min']
				#
				# outside_tempc = wea.get_temperature(u'celsius')[u'temp']
				# outside_temp_maxc = dailyfc[0].get_temperature(u'celsius')[u'max']
				# outside_temp_minc = dailyfc[0].get_temperature(u'celsius')[u'min']
				#
				# # Localize temperature value
				# if pydPiper_config.TEMPERATURE.lower() == u'celsius':
				# 	outside_temp = outside_tempc
				# 	outside_temp_max = int(outside_temp_maxc)
				# 	outside_temp_min = int(outside_temp_minc)
				# 	outside_temp_formatted = u"{0}°C".format(int(outside_temp))
				# 	outside_temp_max_formatted = u"{0}°C".format(int(outside_temp_max))
				# 	outside_temp_min_formatted = u"{0}°C".format(int(outside_temp_min))
				# else:
				# 	outside_temp = outside_tempf
				# 	outside_temp_max = int(outside_temp_maxf)
				# 	outside_temp_min = int(outside_temp_minf)
				# 	outside_temp_formatted = u"{0}°F".format(int(outside_temp))
				# 	outside_temp_max_formatted = u"{0}°F".format(int(outside_temp_max))
				# 	outside_temp_min_formatted = u"{0}°F".format(int(outside_temp_min))
				#
				# outside_conditions = wea.get_detailed_status()
			# except:
			# 	logging.debug(u"Failed to get weather data.  Check OWM_API key.")
			# 	pass


			try:
				with open(u"/sys/class/thermal/thermal_zone0/temp") as file:
					system_tempc = int(file.read())

				# Convert value to float and correct decimal place
				system_tempc = round(float(system_tempc) / 1000,1)

				# convert to fahrenheit
				system_tempf = round(system_tempc*9/5+32,1)

			except AttributeError:
				system_tempc = 0.0
				system_tempf = 0.0

			try:
				if pydPiper_config.TEMPERATURE.lower() == u'celsius':
					system_temp = system_tempc
					system_temp_formatted = u"{0}°c".format(int(system_temp))
				else:
					system_temp = system_tempf
					system_temp_formatted = u"{0}°f".format(int(system_temp))
			except:
				system_temp = system_tempf
				system_temp_formatted = u"{0}°f".format(int(system_temp))

			try:
				# Check if running on OSX.  If yes, adjust df command
				if sys.platform == u"darwin":
					with os.popen(u"df /") as p:
						p = os.popen(u"df /")
						line = p.readline()
						line = p.readline()

					va = line.split()
					line = "{0} {1}".format(va[3], va[4])
				else:
					# assume running on Raspberry linux
					with os.popen(u"df -B 1 /") as p:
						line = p.readline()
						line = p.readline().strip()

				va = line.split()
				avail = int(va[3])
				usedp = int(va[4][:-1]) # Remove trailing % and convert to int
				used = int(va[2])
				availp = 100-usedp

			except AttributeError:
				avail = 0
				availp = 0
				usedp = 0
				used = 0

			with self.musicdata_lock:
				self.musicdata[u'system_temp'] = system_temp
				self.musicdata[u'system_temp_formatted'] = system_temp_formatted

				self.musicdata[u'system_tempc'] = system_tempc
				self.musicdata[u'system_tempf'] = system_tempf

				# For backward compatibility
				self.musicdata[u'current_tempc'] = self.musicdata[u'system_tempc']
				self.musicdata[u'current_tempf'] = self.musicdata[u'system_tempf']

				self.musicdata[u'disk_avail'] = avail
				self.musicdata[u'disk_availp'] = availp
				self.musicdata[u'disk_used'] = used
				self.musicdata[u'disk_usedp'] = usedp


				self.musicdata[u'ip'] = current_ip.decode()

				# For backwards compatibility
				self.musicdata[u'current_ip'] = current_ip.decode()

				self.musicdata[u'outside_temp'] = outside_temp
				self.musicdata[u'outside_temp_max'] = outside_temp_max
				self.musicdata[u'outside_temp_min'] = outside_temp_min
				self.musicdata[u'outside_temp_formatted'] = outside_temp_formatted
				self.musicdata[u'outside_temp_max_formatted'] = outside_temp_max_formatted
				self.musicdata[u'outside_temp_min_formatted'] = outside_temp_min_formatted
				self.musicdata[u'outside_conditions'] = outside_conditions

			# Read environmentals every 5 minutes
			time.sleep(300)
Beispiel #34
0
    def demo(self):

        db = {
            'actPlayer': 'mpd',
            'playlist_position': 1,
            'playlist_length': 5,
            'title': "Nicotine & Gravy",
            'artist': "Beck",
            'album': 'Midnight Vultures',
            'elapsed': 0,
            'length': 400,
            'volume': 50,
            'stream': 'Not webradio',
            'utc': moment.utcnow(),
            'outside_temp_formatted': '46\xb0F',
            'outside_temp_max': 72,
            'outside_temp_min': 48,
            'outside_conditions': 'Windy',
            'system_temp_formatted': '98\xb0C',
            'state': 'stop',
            'system_tempc': 81.0
        }

        dbp = {
            'actPlayer': 'mpd',
            'playlist_position': 1,
            'playlist_length': 5,
            'title': "Nicotine & Gravy",
            'artist': "Beck",
            'album': 'Midnight Vultures',
            'elapsed': 0,
            'length': 400,
            'volume': 50,
            'stream': 'Not webradio',
            'utc': moment.utcnow(),
            'outside_temp_formatted': '46\xb0F',
            'outside_temp_max': 72,
            'outside_temp_min': 48,
            'outside_conditions': 'Windy',
            'system_temp_formatted': '98\xb0C',
            'state': 'stop',
            'system_tempc': 81.0
        }

        events = [(15, 'state', 'play'), (20, 'title', 'Mixed Bizness'),
                  (30, 'volume', 80),
                  (40, 'title', 'I Never Loved a Man (The Way I Love You)'),
                  (40, 'artist', 'Aretha Franklin'),
                  (40, 'album', 'The Queen Of Soul'), (70, 'state', 'stop'),
                  (90, 'state', 'play'),
                  (100, 'title', 'Do Right Woman, Do Right Man'),
                  (120, 'volume', 100), (140, 'state', 'play')]

        starttime = time.time()
        elapsed = int(time.time() - starttime)
        timepos = time.strftime(
            "%-M:%S", time.gmtime(int(elapsed))) + "/" + time.strftime(
                "%-M:%S", time.gmtime(int(254)))

        dc = display.display_controller((80, 16))
        f_path = os.path.join(os.path.dirname(__file__), 'pages_test.py')
        dc.load(f_path, db, dbp)

        starttime = time.time()
        while True:
            elapsed = int(time.time() - starttime)
            db['elapsed'] = elapsed
            db['utc'] = moment.utcnow()
            self.processevent(events, starttime, 'pre', db, dbp)
            img = next(dc)
            self.processevent(events, starttime, 'post', db, dbp)
            lcd.update(img)
            time.sleep(.01)
Beispiel #35
0
    def run(self):

        logging.debug(u"Music Controller Starting")

        # Start the thread that updates the system variables
        sv_t = threading.Thread(target=self.updatesystemvars)
        sv_t.daemon = True
        sv_t.start()
        timesongstarted = 0

        # Inform the system that we are starting up
        with self.musicdata_lock:
            self.musicdata_prev[u'state'] = ''
            self.musicdata[u'state'] = 'starting'
        self.starttime = time.time()

        lastupdate = 0  # Initialize variable to be used to force updates every second regardless of the receipt of a source update
        while not exitapp[0]:

            updates = {}

            # Check if we are starting up.  If yes, update pages to display any start message.
            if self.starttime + pydPiper_config.STARTUP_MSG_DURATION > time.time(
            ):
                time.sleep(pydPiper_config.STARTUP_MSG_DURATION)
                with self.musicdata_lock:
                    self.musicdata['state'] = 'stop'
                continue

            # Attempt to get an update from the queue
            try:
                updates = self.musicqueue.get_nowait()
                self.musicqueue.task_done()
            except Queue.Empty:
                pass

            with self.musicdata_lock:
                # Update musicdata based upon received message
                for item, value in updates.iteritems():
                    self.musicdata[item] = value

                # Update song timing variables
                if u'elapsed' in updates:
                    self.musicdata[u'elapsed'] = self.musicdata[
                        u'current'] = updates[u'elapsed']
                    timesongstarted = time.time() - self.musicdata[u'elapsed']

                if self.musicdata[u'state'] == u'play':
                    if u'elapsed' not in updates:
                        if timesongstarted > 0:
                            self.musicdata[u'elapsed'] = int(time.time() -
                                                             timesongstarted)
                        else:
                            # We got here without timesongstarted being set which is a problem...
                            logging.debug(
                                u"Trying to update current song position with an uninitialized start time"
                            )

                # If the value of current has changed then update the other related timing variables
                if self.musicdata[u'elapsed'] != self.musicdata_prev[
                        u'elapsed']:
                    if self.musicdata[u'length'] > 0:
                        timepos = time.strftime(
                            "%-M:%S", time.gmtime(self.musicdata[u'elapsed'])
                        ) + "/" + time.strftime(
                            "%-M:%S", time.gmtime(self.musicdata[u'length']))
                        remaining = time.strftime(
                            "%-M:%S",
                            time.gmtime(self.musicdata[u'length'] -
                                        self.musicdata[u'elapsed']))
                        timepos_total = time.strftime(
                            "%-M:%S", time.gmtime(self.musicdata[u'length']))
                    else:
                        timepos = time.strftime(
                            "%-M:%S", time.gmtime(self.musicdata[u'elapsed']))
                        remaining = timepos

                    timepos_simple = time.strftime(
                        "%-M:%S", time.gmtime(self.musicdata[u'elapsed']))

                    self.musicdata[u'remaining'] = remaining.decode()
                    self.musicdata[u'elapsed_formatted'] = self.musicdata[
                        u'position'] = timepos.decode()
                    self.musicdata[u'elapsed_simple'] = timepos_simple.decode()
                    self.musicdata[u'total_time'] = timepos_total.decode()

                # Update onoff variables (random, single, repeat)
                self.musicdata[u'random_onoff'] = u"On" if self.musicdata[
                    u'random'] else u"Off"
                self.musicdata[u'single_onoff'] = u"On" if self.musicdata[
                    u'single'] else u"Off"
                self.musicdata[u'repeat_onoff'] = u"On" if self.musicdata[
                    u'repeat'] else u"Off"

            # If anything has changed, update pages
            if self.musicdata != self.musicdata_prev or lastupdate < time.time(
            ):

                # Set lastupdate time to 1 second in the future
                lastupdate = time.time() + 1

                self.musicdata[u'time_formatted'] = moment.utcnow().timezone(
                    pydPiper_config.TIMEZONE).strftime(
                        '%H:%M').strip().decode()
                # To support previous key used for this purpose
                self.musicdata[u'current_time_formatted'] = self.musicdata[
                    u'time_formatted']

                # Update display controller
                # The primary call to this routine is in main but this call is needed to catch variable changes before musicdata_prev is updated.
                self.display_controller.next()

                # Print the current contents of musicdata if showupdates is True
                if self.showupdates:
                    ctime = moment.utcnow().timezone(u"US/Eastern").strftime(
                        "%-I:%M:%S %p").strip()
                    print u"Status at time {0}".format(ctime)

                    with self.musicdata_lock:
                        for item, value in self.musicdata.iteritems():
                            try:
                                print u"    [{0}]={1} {2}".format(
                                    item, repr(value), type(value))
                            except:
                                print u"err"
                                print u"[{0}] =".format(item)
                                print type(value)
                                print repr(value)
                        print u"\n"

                # Update musicdta_prev
                with self.musicdata_lock:
                    for item, value in self.musicdata.iteritems():
                        try:
                            if self.musicdata_prev[item] != value:
                                self.musicdata_prev[item] = value
                        except KeyError:
                            self.musicdata_prev[item] = value

            # Update display data every 1/4 second
            time.sleep(.25)
Beispiel #36
0
    def run(self):

        logging.debug(u"Music Controller Starting")

        self.launch_update_thread(self.updatesystemvars)
        self.launch_update_thread(self.updateconditions)
        self.launch_update_thread(self.updateforecast)

        timesongstarted = 0

        # Inform the system that we are starting up
        with self.musicdata_lock:
            self.musicdata_prev[u'state'] = ''
            self.musicdata[u'state'] = 'starting'
        self.starttime = time.time()

        lastupdate = 0  # Initialize variable to be used to force updates every second regardless of the receipt of a source update
        while not exitapp[0]:

            updates = {}

            # Check if we are starting up.  If yes, update pages to display any start message.
            if self.starttime + pydPiper_config.STARTUP_MSG_DURATION > time.time(
            ):
                time.sleep(pydPiper_config.STARTUP_MSG_DURATION)
                with self.musicdata_lock:
                    self.musicdata['state'] = 'stop'
                continue

            # Attempt to get an update from the queue
            try:
                updates = self.musicqueue.get_nowait()
                self.musicqueue.task_done()
            except Queue.Empty:
                pass

            # Get current time
            try:
                utc = moment.utcnow()
                localtime = moment.utcnow().timezone(pydPiper_config.TIMEZONE)
                current_time_ampm = moment.utcnow().timezone(
                    pydPiper_config.TIMEZONE).strftime(u"%p").strip().decode()
                if pydPiper_config.TIME24HOUR == True:
                    current_time = moment.utcnow().timezone(
                        pydPiper_config.TIMEZONE).strftime(
                            u"%H:%M").strip().decode()
                    current_time_sec = moment.utcnow().timezone(
                        pydPiper_config.TIMEZONE).strftime(
                            u"%H:%M:%S").strip().decode()
                else:
                    current_time = moment.utcnow().timezone(
                        pydPiper_config.TIMEZONE).strftime(
                            u"%-I:%M %p").strip().decode()
                    current_time_sec = moment.utcnow().timezone(
                        pydPiper_config.TIMEZONE).strftime(
                            u"%-I:%M:%S %p").strip().decode()
            except ValueError:
                # Don't know why but on exit, the moment code is occasionally throwing a ValueError
                current_time = u"00:00"
                current_time_sec = u"00:00:00"
                current_time_ampm = u''
                utc = None
                localtime = None

            with self.musicdata_lock:
                # Update musicdata based upon received message
                for item, value in updates.iteritems():
                    self.musicdata[item] = value

                # Update song timing variables
                if u'elapsed' in updates:
                    self.musicdata[u'elapsed'] = self.musicdata[
                        u'current'] = updates[u'elapsed']
                    timesongstarted = time.time() - self.musicdata[u'elapsed']

                if self.musicdata[u'state'] == u'play':
                    if u'elapsed' not in updates:
                        if timesongstarted > 0:
                            self.musicdata[u'elapsed'] = int(time.time() -
                                                             timesongstarted)
                        else:
                            # We got here without timesongstarted being set which is a problem...
                            logging.debug(
                                u"Trying to update current song position with an uninitialized start time"
                            )

                # If the value of current has changed then update the other related timing variables
                if self.musicdata[u'elapsed'] != self.musicdata_prev[
                        u'elapsed']:
                    if self.musicdata[u'length'] > 0:
                        timepos = time.strftime(
                            "%-M:%S", time.gmtime(self.musicdata[u'elapsed'])
                        ) + "/" + time.strftime(
                            "%-M:%S", time.gmtime(self.musicdata[u'length']))
                        remaining = time.strftime(
                            "%-M:%S",
                            time.gmtime(self.musicdata[u'length'] -
                                        self.musicdata[u'elapsed']))

                    else:
                        timepos = time.strftime(
                            "%-M:%S", time.gmtime(self.musicdata[u'elapsed']))
                        remaining = timepos

                    self.musicdata[u'remaining'] = remaining.decode()
                    self.musicdata[u'elapsed_formatted'] = self.musicdata[
                        u'position'] = timepos.decode()

                # Update onoff variables (random, single, repeat)
                self.musicdata[u'random_onoff'] = u"On" if self.musicdata[
                    u'random'] else u"Off"
                self.musicdata[u'single_onoff'] = u"On" if self.musicdata[
                    u'single'] else u"Off"
                self.musicdata[u'repeat_onoff'] = u"On" if self.musicdata[
                    u'repeat'] else u"Off"

                # update time variables
                self.musicdata[u'utc'] = utc
                self.musicdata[u'localtime'] = localtime
                self.musicdata[u'time'] = current_time
                self.musicdata[u'time_ampm'] = current_time_ampm
                # note: 'time_formatted' is computed during page processing as it needs the value of the strftime key contained on the line being displayed

                # For backwards compatibility
                self.musicdata[u'current_time'] = current_time
                self.musicdata[u'current_time_sec'] = current_time

            # If anything has changed, update pages ### probably unnecessary to check this now that time is being updated in this section
            if self.musicdata != self.musicdata_prev or lastupdate < time.time(
            ):

                # Set lastupdate time to 1 second in the future
                lastupdate = time.time() + 1

                self.musicdata[u'time_formatted'] = moment.utcnow().timezone(
                    pydPiper_config.TIMEZONE).strftime(
                        '%H:%M').strip().decode()
                # To support previous key used for this purpose
                self.musicdata[u'current_time_formatted'] = self.musicdata[
                    u'time_formatted']

                # Update display controller
                # The primary call to this routine is in main but this call is needed to catch variable changes before musicdata_prev is updated.
                self.display_controller.next()

                # Print the current contents of musicdata if showupdates is True
                if self.showupdates:

                    # Check to see if a variable has changed (except time variables)
                    shouldshowupdate = False
                    for item, value in self.musicdata.iteritems():
                        try:
                            if item in [
                                    'utc', 'localtime', 'time', 'time_ampm',
                                    'current_time', 'current_time_sec'
                            ]:
                                continue
                            if self.musicdata_prev[item] != value:
                                shouldshowupdate = True
                                break
                        except KeyError:
                            shouldshowupdate = True
                            break

                    if shouldshowupdate:
                        ctime = localtime.strftime("%-I:%M:%S %p").strip()
                        print u"Status at time {0}".format(ctime)

                        with self.musicdata_lock:
                            for item, value in self.musicdata.iteritems():
                                try:
                                    print u"    [{0}]={1} {2}".format(
                                        item, repr(value), type(value))
                                except:
                                    print u"err"
                                    print u"[{0}] =".format(item)
                                    print type(value)
                                    print repr(value)
                            print u"\n"

                # Update musicdata_prev
                with self.musicdata_lock:
                    for item, value in self.musicdata.iteritems():
                        try:
                            if self.musicdata_prev[item] != value:
                                self.musicdata_prev[item] = value
                        except KeyError:
                            self.musicdata_prev[item] = value

            # Update display data every 1/4 second
            time.sleep(.25)
Beispiel #37
0
	db = {
			'actPlayer':'mpd',
			'playlist_position':1,
			'playlist_length':5,
	 		'title':"Nicotine & Gravy",
			'artist':"Beck",
			'album':'Midnight Vultures',
			'tracktype':'MP3 Stereo 24 bit 44.1 Khz',
			'bitdepth':'16 bits',
			'samplerate':'44.1 kHz',
			'elapsed':0,
			'length':400,
			'volume':50,
			'stream':'Not webradio',
			'utc': 	moment.utcnow(),
			'outside_temp_formatted':'46\xb0F',
			'outside_temp_max':72,
			'outside_temp_min':48,
			'outside_conditions':'Windy',
			'system_temp_formatted':'98\xb0C',
			'state':'stop',
			'system_tempc':81.0
		}

	dbp = {
			'actPlayer':'mpd',
			'playlist_position':1,
			'playlist_length':5,
	 		'title':"Nicotine & Gravy",
			'artist':"Beck",
Beispiel #38
0
def since(iso):
  dt = moment.utcnow() - moment.utc(_normalize_tpu_isodate(iso), "%Y-%m-%dT%H:%M:%S.%fZ")
  return dt.total_seconds()
Beispiel #39
0
    def run(self):

        logging.debug(u"Music Controller Starting")

        self.launch_update_thread(self.updatesystemvars)
        self.launch_update_thread(self.updateconditions)
        self.launch_update_thread(self.updateforecast)

        timesongstarted = 0


        # Inform the system that we are starting up
        with self.musicdata_lock:
            self.musicdata_prev[u'state'] = ''
            self.musicdata[u'state'] = 'starting'
        self.starttime = time.time()

        lastupdate = 0 # Initialize variable to be used to force updates every second regardless of the receipt of a source update
        while not exitapp[0]:

            updates = { }

            # Check if we are starting up.  If yes, update pages to display any start message.
            if self.starttime + pydPiper_config.STARTUP_MSG_DURATION > time.time():
                time.sleep(pydPiper_config.STARTUP_MSG_DURATION)
                with self.musicdata_lock:
                    self.musicdata['state'] = 'stop'
                continue

            # Attempt to get an update from the queue
            try:
                updates = self.musicqueue.get_nowait()
                self.musicqueue.task_done()
            except Queue.Empty:
                pass

            # Get current time
            try:
                utc = moment.utcnow()
                localtime = moment.utcnow().timezone(pydPiper_config.TIMEZONE)
                current_time_ampm = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%p").strip().decode()
                if pydPiper_config.TIME24HOUR == True:
                    current_time = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%H:%M").strip().decode()
                    current_time_sec = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%H:%M:%S").strip().decode()
                else:
                    current_time = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%-I:%M %p").strip().decode()
                    current_time_sec = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%-I:%M:%S %p").strip().decode()
            except ValueError:
                # Don't know why but on exit, the moment code is occasionally throwing a ValueError
                current_time = u"00:00"
                current_time_sec = u"00:00:00"
                current_time_ampm = u''
                utc = None
                localtime = None

            with self.musicdata_lock:
                # Update musicdata based upon received message
                for item, value in updates.iteritems():
                    self.musicdata[item] = value

                # Update song timing variables
                if u'elapsed' in updates:
                    self.musicdata[u'elapsed'] = self.musicdata[u'current'] = updates[u'elapsed']
                    timesongstarted = time.time() - self.musicdata[u'elapsed']

                if self.musicdata[u'state'] == u'play':
                    if u'elapsed' not in updates:
                        if timesongstarted > 0:
                            self.musicdata[u'elapsed'] = int(time.time() - timesongstarted)
                        else:
                            # We got here without timesongstarted being set which is a problem...
                            logging.debug(u"Trying to update current song position with an uninitialized start time")

                # If the value of current has changed then update the other related timing variables
                if self.musicdata[u'elapsed'] != self.musicdata_prev[u'elapsed']:
                    if self.musicdata[u'length'] > 0:
                        timepos = time.strftime("%-M:%S", time.gmtime(self.musicdata[u'elapsed'])) + "/" + time.strftime("%-M:%S", time.gmtime(self.musicdata[u'length']))
                        remaining = time.strftime("%-M:%S", time.gmtime(self.musicdata[u'length'] - self.musicdata[u'elapsed'] ) )

                    else:
                        timepos = time.strftime("%-M:%S", time.gmtime(self.musicdata[u'elapsed']))
                        remaining = timepos

                    self.musicdata[u'remaining'] = remaining.decode()
                    self.musicdata[u'elapsed_formatted'] = self.musicdata[u'position'] = timepos.decode()

                # Update onoff variables (random, single, repeat)
                self.musicdata[u'random_onoff'] = u"On" if self.musicdata[u'random'] else u"Off"
                self.musicdata[u'single_onoff'] = u"On" if self.musicdata[u'single'] else u"Off"
                self.musicdata[u'repeat_onoff'] = u"On" if self.musicdata[u'repeat'] else u"Off"

                # update time variables
                self.musicdata[u'utc'] = utc
                self.musicdata[u'localtime'] = localtime
                self.musicdata[u'time'] = current_time
                self.musicdata[u'time_ampm'] = current_time_ampm
                # note: 'time_formatted' is computed during page processing as it needs the value of the strftime key contained on the line being displayed

                # For backwards compatibility
                self.musicdata[u'current_time'] = current_time
                self.musicdata[u'current_time_sec'] = current_time


            # If anything has changed, update pages ### probably unnecessary to check this now that time is being updated in this section
            if self.musicdata != self.musicdata_prev or lastupdate < time.time():

                # Set lastupdate time to 1 second in the future
                lastupdate = time.time()+1

                self.musicdata[u'time_formatted'] = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime('%H:%M').strip().decode()
                # To support previous key used for this purpose
                self.musicdata[u'current_time_formatted'] = self.musicdata[u'time_formatted']

                # Update display controller
                # The primary call to this routine is in main but this call is needed to catch variable changes before musicdata_prev is updated.
                self.display_controller.next()

                # Print the current contents of musicdata if showupdates is True
                if self.showupdates:

                    # Check to see if a variable has changed (except time variables)
                    shouldshowupdate = False
                    for item, value in self.musicdata.iteritems():
                        try:
                            if item in ['utc', 'localtime', 'time', 'time_ampm', 'current_time', 'current_time_sec']:
                                continue
                            if self.musicdata_prev[item] != value:
                                shouldshowupdate = True
                                break
                        except KeyError:
                            shouldshowupdate = True
                            break


                    if shouldshowupdate:
                        ctime = localtime.strftime("%-I:%M:%S %p").strip()
                        print u"Status at time {0}".format(ctime)

                        with self.musicdata_lock:
                            for item,value in self.musicdata.iteritems():
                                try:
                                    print u"    [{0}]={1} {2}".format(item,repr(value), type(value))
                                except:
                                    print u"err"
                                    print u"[{0}] =".format(item)
                                    print type(value)
                                    print repr(value)
                            print u"\n"

                # Update musicdata_prev
                with self.musicdata_lock:
                    for item, value in self.musicdata.iteritems():
                        try:
                            if self.musicdata_prev[item] != value:
                                self.musicdata_prev[item] = value
                        except KeyError:
                            self.musicdata_prev[item] = value

            # Update display data every 1/4 second
            time.sleep(.25)
        beenplaying = True
        currentArtist = ""
        currentTitle = ""
        cpos = ""

        ctime = ""
        hesitate = False
        hesitation_etime = 0
        display_etime = 0
        notplaying_state = "TIME"
        ctime = ""
        hesitation_etime = time.time() + HESITATION_TIME

        while True:
            if TIME24HOUR == True:
                current_time = moment.utcnow().timezone(TIMEZONE).format(
                    "HH:mm").strip()
            else:
                current_time = moment.utcnow().timezone(TIMEZONE).format(
                    "h:m a").strip()

            current_ip = commands.getoutput(
                "ip -4 route get 1 | head -1 | cut -d' ' -f8 | tr -d '\n'"
            ).strip()

            cstatus = rd.status()
            state = cstatus.get('state')

            if state != "play":
                if beenplaying:
                    beenplaying = False
                    currentArtist = ""
Beispiel #41
0
    db = {
        'actPlayer': 'mpd',
        'playlist_position': 1,
        'playlist_length': 5,
        'title': "Nicotine & Gravy",
        'artist': "Beck",
        'album': 'Midnight Vultures',
        'tracktype': 'MP3 Stereo 24 bit 44.1 Khz',
        'bitdepth': '16 bits',
        'samplerate': '44.1 kHz',
        'elapsed': 0,
        'length': 400,
        'volume': 50,
        'stream': 'Not webradio',
        'utc': moment.utcnow(),
        'outside_temp_formatted': '46\xb0F',
        'outside_temp_max': 72,
        'outside_temp_min': 48,
        'outside_conditions': 'Windy',
        'system_temp_formatted': '98\xb0C',
        'state': 'stop',
        'system_tempc': 81.0
    }

    dbp = {
        'actPlayer': 'mpd',
        'playlist_position': 1,
        'playlist_length': 5,
        'title': "Nicotine & Gravy",
        'artist': "Beck",
Beispiel #42
0
import moment
import lib.database as db

# setup now for json
first = moment.utc(2018, 1, 5)
then = moment.utc(2018, 7, 17)
now = moment.utcnow()

#-------------------------------------------------------------------------------- Events
first_flood = db.addEvent("First Boston Flood",
                          id="boston_X8E29",
                          geohash="drt2z",
                          cat="fld",
                          status=3,
                          created_at=first.strftime("%Y-%m-%dT%H:%M:%S"))

second_flood = db.addEvent("Second Boston Flood",
                           id="boston_19EC4",
                           geohash="drt2z",
                           cat="fld",
                           status=3,
                           created_at=then.strftime("%Y-%m-%dT%H:%M:%S"))

active_flood = db.addEvent("Boston Flood",
                           id="boston_D392F",
                           geohash="drt2z",
                           cat="fld",
                           status=1,
                           created_at=now.strftime("%Y-%m-%dT%H:%M:%S"))

#-------------------------------------------------------------------------------- Devices
Beispiel #43
0
class music_controller(threading.Thread):
    # Receives updates from music services
    # Determines what page to displays
    # Sends relevant updates to display_controller

    # musicdata variables.
    # Includes all from musicdata class plus environmentals
    musicdata_init = {
        'state': u"stop",
        'musicdatasource': u"",
        'actPlayer': u"",
        'artist': u"",
        'title': u"",
        'album': u"",
        'uri': u"",
        'current': -1,
        'elapsed': -1,
        'remaining': u"",
        'duration': -1,
        'length': -1,
        'position': u"",
        'elapsed_formatted': u"",
        'volume': -1,
        'repeat': 0,
        'single': 0,
        'random': 0,
        'channels': 0,
        'bitdepth': u"",
        'bitrate': u"",
        'samplerate': u"",
        'type': u"",
        'tracktype': u"",
        'repeat_onoff': u"Off",
        'single_onoff': u"Off",
        'random_onoff': u"Off",
        'playlist_display': u"",
        'playlist_position': -1,
        'playlist_count': -1,
        'playlist_length': -1,
        'current_tempc': 0,
        'current_tempf': 0,
        'disk_avail': 0,
        'disk_availp': 0,
        'current_time': u"",
        'utc': moment.utcnow(),
        'localtime': moment.utcnow().timezone(pydPiper_config.TIMEZONE),
        'current_time_sec': u"",
        'current_time_formatted': u"",
        'time_formatted': u"",
        'current_ip': u"",
        'outside_conditions': 'No data',
        'outside_temp_min': 0,
        'outside_temp_max': 0,
        'outside_temp_formatted': '',
        'system_temp_formatted': ''
    }

    def __init__(self, servicelist, display_controller, showupdates=False):
        threading.Thread.__init__(self)

        self.daemon = True
        self.musicqueue = Queue.Queue()
        self.image = None
        self.showupdates = showupdates
        self.display_controller = display_controller

        self.musicdata = copy.deepcopy(self.musicdata_init)
        self.musicdata_prev = copy.deepcopy(self.musicdata)
        self.servicelist = servicelist
        self.services = {}

        # Attempt to initialize services
        self.initservices()

        # Lock used to prevent simultaneous update of the musicdata dictionary
        self.musicdata_lock = threading.Lock()

    def initservices(self):

        # Make sure that if rune is selected that is is the only service that is selected
        if u"rune" in self.servicelist and len(self.servicelist) > 1:
            logging.critical(u"Rune service can only be used alone")
            raise RuntimeError(u"Rune service can only be used alone")
        if u"volumio" in self.servicelist and len(self.servicelist) > 1:
            logging.critical(u"Volumio service can only be used alone")
            raise RuntimeError(u"Volumio service can only be used alone")

        musicservice = None
        for s in self.servicelist:
            s = s.lower()
            try:
                if s == u"mpd" or s == u"moode":
                    musicservice = sources.musicdata_mpd.musicdata_mpd(
                        self.musicqueue, pydPiper_config.MPD_SERVER,
                        pydPiper_config.MPD_PORT, pydPiper_config.MPD_PASSWORD)
                elif s == u"spop":
                    musicservice = sources.musicdata_spop.musicdata_spop(
                        self.musicqueue, pydPiper_config.SPOP_SERVER,
                        pydPiper_config.SPOP_PORT,
                        pydPiper_config.SPOP_PASSWORD)
                elif s == u"lms":
                    musicservice = sources.musicdata_lms.musicdata_lms(
                        self.musicqueue, pydPiper_config.LMS_SERVER,
                        pydPiper_config.LMS_PORT, pydPiper_config.LMS_USER,
                        pydPiper_config.LMS_PASSWORD,
                        pydPiper_config.LMS_PLAYER)
                elif s == u"rune":
                    musicservice = sources.musicdata_rune.musicdata_rune(
                        self.musicqueue, pydPiper_config.RUNE_SERVER,
                        pydPiper_config.RUNE_PORT,
                        pydPiper_config.RUNE_PASSWORD)
                elif s == u"volumio":
                    musicservice = sources.musicdata_volumio2.musicdata_volumio2(
                        self.musicqueue, pydPiper_config.VOLUMIO_SERVER,
                        pydPiper_config.VOLUMIO_PORT, exitapp)
                else:
                    logging.debug(
                        u"Unsupported music service {0} requested".format(s))
                    continue
            except NameError:
                # Missing dependency for requested servicelist
                logging.warning(
                    u"Request for {0} failed due to missing dependencies".
                    format(s))
                pass
            if musicservice != None:
                self.services[s] = musicservice

        if len(self.services) == 0:
            logging.critical(u"No music services succeeded in initializing")
            raise RuntimeError(u"No music services succeeded in initializing")

    def launch_update_thread(self, func):
        sv_t = threading.Thread(target=func)
        sv_t.daemon = True
        sv_t.start()

    def run(self):

        logging.debug(u"Music Controller Starting")

        self.launch_update_thread(self.updatesystemvars)
        self.launch_update_thread(self.updateconditions)
        self.launch_update_thread(self.updateforecast)

        timesongstarted = 0

        # Inform the system that we are starting up
        with self.musicdata_lock:
            self.musicdata_prev[u'state'] = ''
            self.musicdata[u'state'] = 'starting'
        self.starttime = time.time()

        lastupdate = 0  # Initialize variable to be used to force updates every second regardless of the receipt of a source update
        while not exitapp[0]:

            updates = {}

            # Check if we are starting up.  If yes, update pages to display any start message.
            if self.starttime + pydPiper_config.STARTUP_MSG_DURATION > time.time(
            ):
                time.sleep(pydPiper_config.STARTUP_MSG_DURATION)
                with self.musicdata_lock:
                    self.musicdata['state'] = 'stop'
                continue

            # Attempt to get an update from the queue
            try:
                updates = self.musicqueue.get_nowait()
                self.musicqueue.task_done()
            except Queue.Empty:
                pass

            # Get current time
            try:
                utc = moment.utcnow()
                localtime = moment.utcnow().timezone(pydPiper_config.TIMEZONE)
                current_time_ampm = moment.utcnow().timezone(
                    pydPiper_config.TIMEZONE).strftime(u"%p").strip().decode()
                if pydPiper_config.TIME24HOUR == True:
                    current_time = moment.utcnow().timezone(
                        pydPiper_config.TIMEZONE).strftime(
                            u"%H:%M").strip().decode()
                    current_time_sec = moment.utcnow().timezone(
                        pydPiper_config.TIMEZONE).strftime(
                            u"%H:%M:%S").strip().decode()
                else:
                    current_time = moment.utcnow().timezone(
                        pydPiper_config.TIMEZONE).strftime(
                            u"%-I:%M %p").strip().decode()
                    current_time_sec = moment.utcnow().timezone(
                        pydPiper_config.TIMEZONE).strftime(
                            u"%-I:%M:%S %p").strip().decode()
            except ValueError:
                # Don't know why but on exit, the moment code is occasionally throwing a ValueError
                current_time = u"00:00"
                current_time_sec = u"00:00:00"
                current_time_ampm = u''
                utc = None
                localtime = None

            with self.musicdata_lock:
                # Update musicdata based upon received message
                for item, value in updates.iteritems():
                    self.musicdata[item] = value

                # Update song timing variables
                if u'elapsed' in updates:
                    self.musicdata[u'elapsed'] = self.musicdata[
                        u'current'] = updates[u'elapsed']
                    timesongstarted = time.time() - self.musicdata[u'elapsed']

                if self.musicdata[u'state'] == u'play':
                    if u'elapsed' not in updates:
                        if timesongstarted > 0:
                            self.musicdata[u'elapsed'] = int(time.time() -
                                                             timesongstarted)
                        else:
                            # We got here without timesongstarted being set which is a problem...
                            logging.debug(
                                u"Trying to update current song position with an uninitialized start time"
                            )

                # If the value of current has changed then update the other related timing variables
                if self.musicdata[u'elapsed'] != self.musicdata_prev[
                        u'elapsed']:
                    if self.musicdata[u'length'] > 0:
                        timepos = time.strftime(
                            "%-M:%S", time.gmtime(self.musicdata[u'elapsed'])
                        ) + "/" + time.strftime(
                            "%-M:%S", time.gmtime(self.musicdata[u'length']))
                        remaining = time.strftime(
                            "%-M:%S",
                            time.gmtime(self.musicdata[u'length'] -
                                        self.musicdata[u'elapsed']))

                    else:
                        timepos = time.strftime(
                            "%-M:%S", time.gmtime(self.musicdata[u'elapsed']))
                        remaining = timepos

                    self.musicdata[u'remaining'] = remaining.decode()
                    self.musicdata[u'elapsed_formatted'] = self.musicdata[
                        u'position'] = timepos.decode()

                # Update onoff variables (random, single, repeat)
                self.musicdata[u'random_onoff'] = u"On" if self.musicdata[
                    u'random'] else u"Off"
                self.musicdata[u'single_onoff'] = u"On" if self.musicdata[
                    u'single'] else u"Off"
                self.musicdata[u'repeat_onoff'] = u"On" if self.musicdata[
                    u'repeat'] else u"Off"

                # update time variables
                self.musicdata[u'utc'] = utc
                self.musicdata[u'localtime'] = localtime
                self.musicdata[u'time'] = current_time
                self.musicdata[u'time_ampm'] = current_time_ampm
                # note: 'time_formatted' is computed during page processing as it needs the value of the strftime key contained on the line being displayed

                # For backwards compatibility
                self.musicdata[u'current_time'] = current_time
                self.musicdata[u'current_time_sec'] = current_time

            # If anything has changed, update pages ### probably unnecessary to check this now that time is being updated in this section
            if self.musicdata != self.musicdata_prev or lastupdate < time.time(
            ):

                # Set lastupdate time to 1 second in the future
                lastupdate = time.time() + 1

                self.musicdata[u'time_formatted'] = moment.utcnow().timezone(
                    pydPiper_config.TIMEZONE).strftime(
                        '%H:%M').strip().decode()
                # To support previous key used for this purpose
                self.musicdata[u'current_time_formatted'] = self.musicdata[
                    u'time_formatted']

                # Update display controller
                # The primary call to this routine is in main but this call is needed to catch variable changes before musicdata_prev is updated.
                self.display_controller.next()

                # Print the current contents of musicdata if showupdates is True
                if self.showupdates:

                    # Check to see if a variable has changed (except time variables)
                    shouldshowupdate = False
                    for item, value in self.musicdata.iteritems():
                        try:
                            if item in [
                                    'utc', 'localtime', 'time', 'time_ampm',
                                    'current_time', 'current_time_sec'
                            ]:
                                continue
                            if self.musicdata_prev[item] != value:
                                shouldshowupdate = True
                                break
                        except KeyError:
                            shouldshowupdate = True
                            break

                    if shouldshowupdate:
                        ctime = localtime.strftime("%-I:%M:%S %p").strip()
                        print u"Status at time {0}".format(ctime)

                        with self.musicdata_lock:
                            for item, value in self.musicdata.iteritems():
                                try:
                                    print u"    [{0}]={1} {2}".format(
                                        item, repr(value), type(value))
                                except:
                                    print u"err"
                                    print u"[{0}] =".format(item)
                                    print type(value)
                                    print repr(value)
                            print u"\n"

                # Update musicdata_prev
                with self.musicdata_lock:
                    for item, value in self.musicdata.iteritems():
                        try:
                            if self.musicdata_prev[item] != value:
                                self.musicdata_prev[item] = value
                        except KeyError:
                            self.musicdata_prev[item] = value

            # Update display data every 1/4 second
            time.sleep(.25)

    def checkweatherconfiguration(self):
        if not pydPiper_config.WEATHER_SERVICE:
            logging.debug('Weather service not enabled')
            return False

        if pydPiper_config.WEATHER_SERVICE not in [
                'wunderground', 'accuweather'
        ]:
            logging.warning('{0} is not a valid weather service'.format(
                pydPiper_config.WEATHER_SERVICE))
            return False

        if not pydPiper_config.WEATHER_API:
            logging.warning(
                'Weather service requires an API key.  Weather services will not be available until one is provided'
            )
            return False

        if not pydPiper_config.WEATHER_LOCATION:
            logging.warning(
                'Weather service requires that a location be specified.  Weather services will not be available until one is provided'
            )
            return False
        return True

    def checkaccuweatherreturn(self, status_code):
        if status_code == 400:
            logging.warning(
                'Request had bad syntax or the parameters supplied were invalid.  Request was [{0}]'
                .format(querystr))
        elif status_code == 401:
            logging.warning(
                'Unauthorized. API authorization failed.  API key is [{0}]'.
                format(pydPiper_config.WEATHER_API))
        elif status_code == 403:
            logging.warning(
                'Unauthorized. You do not have permission to access this endpoint'
            )
        elif status_code == 404:
            logging.warning(
                'Server has not found a route matching the given URI.  Request was [{0}]'
                .format(querystr))
        elif status_code == 500:
            logging.warning(
                'Server encountered an unexpected condition which prevented it from fulfilling the request.  Request was [{0}]'
                .format(querystr))
        elif status_code == 200:
            return True
        else:
            logging.warning(
                'An unexpected return value was provide.  Value was [{0}]. Request was [{1}]'
                .format(status_code, querystr))
        return False

    def updateforecast(self):
        if not self.checkweatherconfiguration():
            return

        logging.debug(
            'Initializing weather forecast update process.  Forecasts will update every 12 hours at noon and midnight'
        )

        while not exitapp[0]:
            updateFlag = False

            logging.debug('Requesting weather forecast from {0}'.format(
                pydPiper_config.WEATHER_SERVICE))
            if pydPiper_config.WEATHER_SERVICE == 'accuweather':
                querystr = 'http://dataservice.accuweather.com/forecasts/v1/daily/1day/' + pydPiper_config.WEATHER_LOCATION
                r = requests.get(querystr, {
                    'apikey': pydPiper_config.WEATHER_API,
                })

                if self.checkaccuweatherreturn(r.status_code):
                    try:
                        res = r.json()
                        todaysForecast = res['DailyForecasts'][0]

                        temp_max_f = todaysForecast['Temperature']['Maximum'][
                            'Value'] if todaysForecast['Temperature'][
                                'Maximum']['Unit'] == 'F' else round(
                                    (todaysForecast['Temperature']['Maximum']
                                     ['Value'] * 1.8) + 32, 1)
                        temp_min_f = todaysForecast['Temperature']['Minimum'][
                            'Value'] if todaysForecast['Temperature'][
                                'Minimum']['Unit'] == 'F' else round(
                                    (todaysForecast['Temperature']['Minimum']
                                     ['Value'] * 1.8) + 32, 1)
                        outside_temp_max = temp_max_f if pydPiper_config.TEMPERATURE.lower(
                        ) == 'fahrenheit' else round(
                            (temp_max_f - 32) * 0.55555556, 1)
                        outside_temp_min = temp_min_f if pydPiper_config.TEMPERATURE.lower(
                        ) == 'fahrenheit' else round(
                            (temp_min_f - 32) * 0.55555556, 1)
                        outside_temp_max_formatted = u"{0}°{1}".format(
                            int(outside_temp_max), {
                                'fahrenheit': 'F',
                                'celsius': 'C'
                            }.get(pydPiper_config.TEMPERATURE.lower()))
                        outside_temp_min_formatted = u"{0}°{1}".format(
                            int(outside_temp_min), {
                                'fahrenheit': 'F',
                                'celsius': 'C'
                            }.get(pydPiper_config.TEMPERATURE.lower()))
                        outside_conditions = todaysForecast['Day'][
                            'IconPhrase']
                        updateFlag = True
                    except (KeyError, IndexError, ValueError):
                        logging.warning(
                            'AccuWeather provided a response in an unexpected format.  Received [{0}]'
                            .format(res))

            if updateFlag:
                logging.debug(
                    'Forecast calls for a high of {0}, a low of {1}.  Condition is {2}'
                    .format(outside_temp_max_formatted,
                            outside_temp_min_formatted, outside_conditions))
                with self.musicdata_lock:
                    self.musicdata[u'outside_temp_max'] = outside_temp_max
                    self.musicdata[u'outside_temp_min'] = outside_temp_min
                    self.musicdata[
                        u'outside_temp_max_formatted'] = outside_temp_max_formatted
                    self.musicdata[
                        u'outside_temp_min_formatted'] = outside_temp_min_formatted
                    self.musicdata[u'outside_conditions'] = outside_conditions

            # Sleep until next update which occurs every half day
            pause.sleepUntil(time.time() + pause.nextHalfday(60), exitapp)

    def updateconditions(self):
        if not self.checkweatherconfiguration():
            return

        logging.debug(
            'Initializing weather current conditions update process.  Current conditions will update every hour'
        )

        while not exitapp[0]:
            updateFlag = False
            # If using accuweather, sample current condition date every hour
            if pydPiper_config.WEATHER_SERVICE == 'accuweather':
                logging.debug('Requesting current conditions from {0}'.format(
                    pydPiper_config.WEATHER_SERVICE))
                querystr = 'http://dataservice.accuweather.com/currentconditions/v1/' + pydPiper_config.WEATHER_LOCATION
                r = requests.get(querystr,
                                 {'apikey': pydPiper_config.WEATHER_API})

                if self.checkaccuweatherreturn(r.status_code):
                    try:
                        res = r.json()
                        current_observation = res[0]

                        temp = current_observation['Temperature']['Imperial'][
                            'Value'] if pydPiper_config.TEMPERATURE.lower(
                            ) == 'fahrenheit' else current_observation[
                                'Temperature']['Metric']['Value']
                        temp_formatted = u"{0}°{1}".format(
                            int(temp), {
                                'fahrenheit': 'F',
                                'celsius': 'C'
                            }.get(pydPiper_config.TEMPERATURE.lower()))
                        updateFlag = True
                    except (KeyError, IndexError, ValueError):
                        logging.warning(
                            'AccuWeather provided a response in an unexpected format.  Received [{0}]'
                            .format(res))

                    if updateFlag:
                        logging.debug('Current Temperature is {0}'.format(
                            temp_formatted))
                        with self.musicdata_lock:
                            self.musicdata[u'outside_temp'] = temp
                            self.musicdata[
                                u'outside_temp_formatted'] = temp_formatted

            # If using Weather Undergroun, sample current and forecast condition date every hour
            elif pydPiper_config.WEATHER_SERVICE == 'wunderground':
                querystr = 'http://api.wunderground.com/api/' + pydPiper_config.WEATHER_API + '/geolookup/conditions/forecast/q/' + pydPiper_config.WEATHER_LOCATION + '.json'
                r = requests.get(querystr)

                if self.checkaccuweatherreturn(r.status_code):
                    try:
                        res = r.json()
                        if 'error' in res['response']:
                            logging.warning(
                                'Error occured retrieving forecast from Weather Underground.  Problem type was [{0}]:[{1}]'
                                .format(
                                    res['response']['error']['type'],
                                    res['response']['error']['description']))
                        else:
                            todaysForecast = res['forecast']['simpleforecast'][
                                'forecastday'][0]
                            currentObservation = res['current_observation']

                            temp = currentObservation[
                                'temp_f'] if pydPiper_config.TEMPERATURE.lower(
                                ) == 'fahrenheit' else currentObservation[
                                    'temp_c']
                            temp_formatted = u"{0}°{1}".format(
                                int(temp), {
                                    'fahrenheit': 'F',
                                    'celsius': 'C'
                                }.get(pydPiper_config.TEMPERATURE.lower()))

                            temp_max_f = round(
                                float(todaysForecast['high']['fahrenheit']), 1)
                            temp_min_f = round(
                                float(todaysForecast['low']['fahrenheit']), 1)
                            temp_max_c = round(
                                float(todaysForecast['high']['celsius']), 1)
                            temp_min_c = round(
                                float(todaysForecast['low']['celsius']), 1)
                            outside_temp_max = temp_max_f if pydPiper_config.TEMPERATURE.lower(
                            ) == 'fahrenheit' else temp_max_c
                            outside_temp_min = temp_min_f if pydPiper_config.TEMPERATURE.lower(
                            ) == 'fahrenheit' else temp_min_c
                            outside_temp_max_formatted = u"{0}°{1}".format(
                                int(outside_temp_max), {
                                    'fahrenheit': 'F',
                                    'celsius': 'C'
                                }.get(pydPiper_config.TEMPERATURE.lower()))
                            outside_temp_min_formatted = u"{0}°{1}".format(
                                int(outside_temp_min), {
                                    'fahrenheit': 'F',
                                    'celsius': 'C'
                                }.get(pydPiper_config.TEMPERATURE.lower()))
                            outside_conditions = currentObservation['weather']
                            updateFlag = True
                    except (KeyError, IndexError, ValueError):
                        logging.warning(
                            'Weather Underground provided a response in an unexpected format.  Received [{0}]'
                            .format(res))

                    if updateFlag:
                        logging.debug('Current Temperature is {0}'.format(
                            temp_formatted))
                        with self.musicdata_lock:
                            self.musicdata[u'outside_temp'] = temp
                            self.musicdata[
                                u'outside_temp_formatted'] = temp_formatted
                            self.musicdata[
                                u'outside_temp_max'] = outside_temp_max
                            self.musicdata[
                                u'outside_temp_min'] = outside_temp_min
                            self.musicdata[
                                u'outside_temp_max_formatted'] = outside_temp_max_formatted
                            self.musicdata[
                                u'outside_temp_min_formatted'] = outside_temp_min_formatted
                            self.musicdata[
                                u'outside_conditions'] = outside_conditions

            # Sleep until next update which occurs every hour
            pause.sleepUntil(time.time() + pause.nextHour(60), exitapp)

    def updatesystemvars(self):
        logging.debug(
            'Initializing current system status update process.  System status will update every five minutes'
        )

        while not exitapp[0]:

            current_ip = commands.getoutput(
                u"ip -4 route get 1 | head -1 | cut -d' ' -f8 | tr -d '\n'"
            ).strip()

            try:
                with open(u"/sys/class/thermal/thermal_zone0/temp") as file:
                    system_tempc = int(file.read())

                # Convert value to float and correct decimal place
                system_tempc = round(float(system_tempc) / 1000, 1)

                # convert to fahrenheit
                system_tempf = round(system_tempc * 9 / 5 + 32, 1)

            except AttributeError:
                system_tempc = 0.0
                system_tempf = 0.0

            try:
                if pydPiper_config.TEMPERATURE.lower() == u'celsius':
                    system_temp = system_tempc
                    system_temp_formatted = u"{0}°c".format(int(system_temp))
                else:
                    system_temp = system_tempf
                    system_temp_formatted = u"{0}°f".format(int(system_temp))
            except:
                system_temp = system_tempf
                system_temp_formatted = u"{0}°f".format(int(system_temp))

            try:
                # Check if running on OSX.  If yes, adjust df command
                with os.popen(u'cat /etc/os-release') as p:
                    releaseName = p.readline()

                if sys.platform == u"darwin":
                    with os.popen(u"df /") as p:
                        p = os.popen(u"df /")
                        line = p.readline()
                        line = p.readline()

                    va = line.split()
                    line = "{0} {1}".format(va[3], va[4])

                    va = line.split()
                    avail = int(va[3])
                    usedp = int(
                        va[4][:-1])  # Remove trailing % and convert to int
                    used = int(va[2])
                    availp = 100 - usedp

                elif releaseName[6:12] == 'Alpine':
                    with os.popen(u"df /") as p:
                        p = os.popen(u"df -B 1 /")
                        line = p.readline()
                        line = p.readline()
                        line = p.readline()

                        va = line.split()
                        avail = int(va[2])
                        usedp = int(
                            va[3][:-1])  # Remove trailing % and convert to int
                        used = int(va[1])
                        availp = 100 - usedp
                else:
                    # assume running on Raspberry linux
                    with os.popen(u"df -B 1 /") as p:
                        line = p.readline()
                        line = p.readline().strip()

                    va = line.split()
                    avail = int(va[3])
                    usedp = int(
                        va[4][:-1])  # Remove trailing % and convert to int
                    used = int(va[2])
                    availp = 100 - usedp

            except AttributeError:
                avail = 0
                availp = 0
                usedp = 0
                used = 0

            logging.debug(
                'System status: Temp {0}, Disk space remaining {1}%, IP address {2}'
                .format(system_temp_formatted, availp, current_ip.decode()))
            with self.musicdata_lock:
                self.musicdata[u'system_temp'] = system_temp
                self.musicdata[
                    u'system_temp_formatted'] = system_temp_formatted

                self.musicdata[u'system_tempc'] = system_tempc
                self.musicdata[u'system_tempf'] = system_tempf

                # For backward compatibility
                self.musicdata[u'current_tempc'] = self.musicdata[
                    u'system_tempc']
                self.musicdata[u'current_tempf'] = self.musicdata[
                    u'system_tempf']

                self.musicdata[u'disk_avail'] = avail
                self.musicdata[u'disk_availp'] = availp
                self.musicdata[u'disk_used'] = used
                self.musicdata[u'disk_usedp'] = usedp

                self.musicdata[u'ip'] = current_ip.decode()

                # For backwards compatibility
                self.musicdata[u'current_ip'] = current_ip.decode()

            # Sleep until next update which occurs every minutes
            pause.sleepUntil(time.time() + 300, exitapp)
Beispiel #44
0
def now():
    return moment.utcnow()