示例#1
0
def main():
    fan = OutputDevice(18)
    while True:
        temp = int(vc.measure_temp())
        print(temp)
        if  temp >= 50:
            fan.on()
            print("fan.on()")
        elif temp <= 45:
            fan.off()
            print("fan.off()")
        time.sleep(1)
示例#2
0
def get_temps():
    """Get measured temperatures from envirophat and raspberry pi CPU sensor.
    Calculate offset measured temp. Format for further use.
    """
    global cpu_temp
    global temp
    global tempmed
    global temp_calibrated

    cpu_temp = vcgencmd.measure_temp()

    temp = weather.temperature()
    temp_calibrated = temp - ((cpu_temp - temp)/factor)
    tempmed = '{:.1f}'.format(round(temp_calibrated, 2))
示例#3
0
def get_temps():
    """Get measured temperatures from envirophat and raspberry pi CPU sensor.
    Calculate offset measured temp. Format for further use.
    """
    logger.debug('Calculating temperatures.')

    global cpu_temp
    global temp
    global tempmed
    global temp_calibrated

    cpu_temp = vcgencmd.measure_temp()

    temp = weather.temperature()
    temp_calibrated = temp - ((cpu_temp - temp) / factor)
    tempmed = '{:.1f}'.format(round(temp_calibrated, 2))
示例#4
0
def ReportDeviceInfo(_ip, _port):
    client = udp_client.SimpleUDPClient(_ip, int(_port))
    path = "/home/pi/rpi-ws281x-python-and-osc"
    repo = git.Repo(path, search_parent_directories=True)
    sha = repo.head.object.hexsha
    total, used, free = shutil.disk_usage("/")
    _strTotal = "Total: %6.2f GB" % (total / (2**30))
    _strUsed = "Used: %6.2f GB" % (used / (2**30))
    CPUc = vcgencmd.measure_temp()
    InformationStr = "CPU:" + str(
        CPUc) + ",Hard Disk " + _strTotal + " " + _strUsed
    temp_list = [
        GetLocalIp(), LeshLib.MyOscPort, sha, LeshLib.JsonTimestamp,
        InformationStr
    ]
    client.send_message("/Response", temp_list)
示例#5
0
    def measure(self):
        coretemp = vcgencmd.measure_temp()
        clock_core = vcgencmd.measure_clock("core")
        timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()

        measurements = list()
        measurements.append({
            "measurement": "coretemp",
            "time": timestamp,
            "fields": {
                "value": coretemp
            }
        })

        measurements.append({
            "measurement": "clock_core",
            "time": timestamp,
            "fields": {
                "value": clock_core
            }
        })

        return measurements
示例#6
0
                            raise ValueError(
                                'This system does not appear to be a '
                                'Raspberry Pi.')
                        else:
                            return False
            if not found:
                if raise_on_errors:
                    raise ValueError(
                        'Unable to determine if this system is a Raspberry Pi.'
                    )
                else:
                    return False
    except IOError:
        if raise_on_errors:
            raise ValueError('Unable to open `/proc/cpuinfo`.')
        else:
            return False

    return True


IS_RASPBERRY_PI = is_raspberry_pi()

if IS_RASPBERRY_PI:
    value = (vcgencmd.measure_temp())
    rom = 'raspberrypi'
    type = 'temp'
    name = 'raspberrypi'
    data = insert(rom, type, value, name)
    data.request()
示例#7
0
# *-* coding: utf-8 -*-
from __future__ import print_function
import vcgencmd
import requests
import os
import time

temp_limit = 50
notify_interval = 30
log_file_path = '/home/pi/pi-scripts/pitemp.log'

with open('/home/pi/.maker_key', 'r') as key_file:
    maker_key = key_file.read()

cpu_temp = vcgencmd.measure_temp()

if os.path.isfile(log_file_path) == False:
    with open(log_file_path, 'w') as log_file:
        log_file.write('%s' % time.time())

with open(log_file_path, 'r') as log_file:
    time_last_notif = float(log_file.read())

maker_url = 'https://maker.ifttt.com/trigger/pitemp/with/key/' + maker_key + '?value1=' + str(
    cpu_temp)
content = requests.get(maker_url).text
print(content)

if cpu_temp > temp_limit:
    time_now = time.time()
    if time_now > time_last_notif + notify_interval:
示例#8
0
import vcgencmd as vc

GPIO.setmode(GPIO.BOARD)
GPIO.setup(fanPin, GPIO.OUT)
GPIO.setwarnings(False)

pwm = GPIO.PWM(fanPin, 100)

e = threading.Event()
stop = False


def handler_signals(sig, frame):
    global stop
    e.set()
    stop = True


signal.signal(signal.SIGTERM, handler_signals)
signal.signal(signal.SIGINT, handler_signals)

while not stop:
    temp = int(vc.measure_temp())
    if temp >= tempHigh:
        pwm.start(100)
    elif temp <= tempLow:
        pwm.start(0)
    e.wait(timeout=sleeptime)

GPIO.cleanup()
示例#9
0
 def DisplayTemperature(self):
     outItem = "\n" + str(vcgencmd.measure_temp()) + "C\n"
     return outItem
示例#10
0
    def do_GET(self):

        global server_instance_id
        global video_stream
        global video_stream_360

        rootdir = guess_script_file_directory()
        try:
            print('self.path {}, thread {}'.format(
                self.path,
                threading.current_thread().ident))
            print('� cookie: {}'.format(self.headers.get('Cookie')))

            #logging.info('#HEADERS (as string): ',self.headers.as_string())
            #logging.info('#HEADERS (items): ',self.headers.items())

            # Check if the path has either
            # 1. has a valid sesison info, or
            # 2. a static resource or a script which is not an html file.
            # - 2 allows .js/.jpg/ files to be returned without session info (no way to request these with session info)
            #   whereas index.html and other API calls (motor controls, etc) require session info
            if self.validate_session_info(self.headers):
                print('✓ valid sid')
                logging.debug('✓ valid sid')
                pass
            elif self.path.startswith('/auth'):
                print('🔑 Authenticating.')
                logging.debug('🔑 Authenticating.')

                # SID was not found in the cookie
                # If this is a valid auth request, the header should contain a password

                registered = self.register_client(self.headers)

                if registered:
                    # Authenticated; response was set in register_client() so we just return now
                    return
                else:
                    # Either the password was wrong or there was no password in the header
                    logging.debug(
                        'authentication failed. Returning an empty string instead of a session ID'
                    )
                    self.send_response_and_header('text/plain', 0)
                return

            else:
                print('login is required')
                logging.debug('login is required')
                self.return_login_page()
                return

            if self.path.startswith('/auth'):
                # The header contains a valid SID but '/auth' is requested.
                # This happens when the client is already authenticated but it somehow sent the /auth path
                client_sid = self.get_sid_from_cookie(self.headers)
                print(
                    'Authentication request from a client which already has an sid: {}'
                    .format(client_sid))
                logging.debug(
                    'Authentication request from a client which already has an sid: {}'
                    .format(client_sid))

                self.send_dict_as_json(
                    {'auth_status': 'already-authenticated'})
                logging.debug('returning "already authenticated" status')
                return
            elif self.path.startswith('/siid'):
                send_dict_as_json({'siid': server_instance_id})
                return
            if self.path.startswith('/forward'):
                logging.debug('driving forward')
                motor_control.start_motor_forward(10)
            elif self.path.startswith('/stop'):
                logging.debug('stopping the motor')
                motor_control.stop_motor()
                motor_control.set_steering(0)
            elif self.path.startswith('/backward'):
                logging.debug('driving backward')
                motor_control.start_motor_backward(10)
            elif self.path.startswith('/steer'):
                logging.debug('steering {}'.format(str(self.path)))
                if 0 <= self.path.find('dir=left'):
                    motor_control.set_steering(90)
                elif 0 <= self.path.find('dir=right'):
                    motor_control.set_steering(-90)
            #elif self.path.startswith('/reset'):
            #print('Resetting')
            #motor_control.stop_motor()
            elif self.path.startswith('/take_photo'):
                print('Taking a photo')
                take_photo()
            elif self.path.startswith('/pin'):

                #if not self.is_admin(self.headers):
                #  return

                pin = {"pin": self.get_guest_password()}
                text = json.dumps(pin)
                print('Returning pin info: {}'.format(str(text)))
                logging.debug('Returning pin info: {}'.format(str(text)))
                encoded = text.encode('utf-8')
                self.send_response_and_header('application/json', len(encoded))
                self.wfile.write(encoded)
                self.wfile.flush()
                return

            elif self.path.startswith('/shutdown'):
                print('shutdown request received')
                #subprocess.check_output('sudo shutdown now')
                pass
            elif self.path.startswith('/reboot'):
                print('reboot request received')
                pass
            elif self.path.startswith('/hw-status'):
                print('Querying server hardware status.')
                hw_status = {
                    "uptime": get_uptime(),
                    "temp": vcgencmd.measure_temp(),
                    "cpu_usage": psutil.cpu_percent(),
                    "camera": {
                        "supported": vcgencmd.get_camera('supported'),
                        "detected": vcgencmd.get_camera('detected')
                    },
                    "ip": '0.1.2.3',
                    "public_ip": '4.5.6.7'
                }

                text = json.dumps(hw_status)
                #text = '<?xml version="1.0" encoding="UTF-8"?>\n<abc>123</abc>'
                print('hw_status: ' + text)
                encoded = text.encode('utf-8')
                self.send_response_and_header('application/json', len(encoded))
                self.wfile.write(encoded)
                self.wfile.flush()
                return

            elif self.path.startswith('/reset_device'):
                video_stream_360.close()  # Close the device
                time.sleep(3)
                usbutil.reset_device(server_params['spherical_camera_id']
                                     )  # Reset the camera device
                time.sleep(3)
                video_stream_360 = VideoStream.VideoStream(
                    server_params['spherical_camera'])
                print('Device was reset.')
                return

            elif self.path == '/stream.mjpg':
                video_stream.start_streaming(self)

            elif self.path == '/stream360.mjpg':
                video_stream_360.start_streaming(self)

            elif self.path.startswith('/stream?'):
                op = self.path[len('/stream?'):]
                self.control_stream(video_stream, op)
                encoded = json.dumps({"nyanko": 0}).encode('utf-8')
                self.send_response_and_header('application/json', len(encoded))
                self.wfile.write(encoded)
                self.wfile.flush()
                return

            elif self.path.startswith('/stream360?'):
                op = self.path[len('/stream360?'):]
                self.control_stream(video_stream_360, op)
                encoded = json.dumps({"nyanko": 0}).encode('utf-8')
                self.send_response_and_header('application/json', len(encoded))
                self.wfile.write(encoded)
                self.wfile.flush()
                return

            else:
                print('Delegating request to super class (path: {})'.format(
                    self.path))
                logging.info(
                    'Delegating request to super class (path: {})'.format(
                        self.path))
                super(NyankoRoverHTTPRequestHandler, self).do_GET()

        except IOError:
            motor_control.stop_motor()
            self.send_error(404, 'file not found')
示例#11
0
red = (255, 0, 0)
green = (0, 255, 0)
sense.set_rotation(180)

def lowLighttrue():
      sense.low_light = True 

def lowLightfalse():
      sense.low_light = False

while True:

  t = sense.get_temperature()
  p = sense.get_pressure()
  h = sense.get_humidity()
  CPUc=vcgencmd.measure_temp()
  t = round(t, 1)
  p = round(p, 1)
  h = round(h, 1)

  CPUc = round(CPUc,1)
  r = requests.get('http://api.openweathermap.org/data/2.5/weather?id=5134086&APPID=616ffe1395e0e036d47b0e5982b5bc80')
  result=r.json() 
  main=result["weather"][0]["main"]
  desc=result["weather"][0]["description"]
  icon=result["weather"][0]["icon"]
  icon_request=requests.get("http://openweathermap.org/img/w/"+icon+".png")
  with open(icon+'.png', 'wb') as f:
        f.write(icon_request.content)
  with open(icon+'.png', 'r+b') as f:
    with Image.open(f) as image:
import vcgencmd
import random
import time

Res=2
Tim = time.time()
#CPUc=vcgencmd.measure_temp()
#print str(CPUc)
Mod1 = 0
Sol1 = random.randint(0,7)
Sol2 = random.randint(0,9)
Sol3 = random.randint(4,6)
Sol4 = random.randint(4,6)
Bat1 = random.randint(5,9)
Bat2 = random.randint(5,6)
Tem1 = vcgencmd.measure_temp()
Tem2 = random.randint(-30,60)

print(Sol1)
print(Sol2)
print(Sol3)
print(Sol3)
print(Sol4)
print(Bat1)
print(Bat2)
print(Tem1)
print(str(Tem2))
print(Res)
print(Tim)
#'FROMCALL>TOCALL::ADDRCALL :message text'
file = open("aprs_telemetry.txt","w")