예제 #1
0
def on_message(client, userdata, message):
    if config.MQTT_SERVER != "mqtt.eclipse.org":  #deactivate for demo server
        msg = message.payload.decode("utf-8")
        print("message received ", str(msg))
        print("message topic=", message.topic)
        print("message qos=", message.qos)
        print("message retain flag=", message.retain)

        if message.topic.startswith(config.MQTT_PATH + "/set/relais"):
            channel = int(message.topic[-1])
            assert 0 < channel < 4, 'channel outside 1..3'
            if msg == 'ON':
                peripherals.controlrelays(channel, 1)
                publish("relais" + channel, 'ON')
            elif msg == 'OFF':
                peripherals.controlrelays(channel, 0)
                publish("relais" + channel, 'OFF')
            else:
                print('unknown:' + message.topic + ' message:' + msg)

        if message.topic == (config.MQTT_PATH + "/set/buzzer"):

            if msg == 'ON':
                peripherals.controlrelays(4, 1)
                publish("buzzer", 'ON')
            elif msg == 'OFF':
                peripherals.controlrelays(4, 0)
                publish("buzzer", 'OFF')
            else:
                print('unknown:' + message.topic + ' message:' + msg)

        if message.topic == (config.MQTT_PATH + "/set/d13"):

            if msg == 'ON':
                peripherals.controlrelays(5, 1)
                publish("d13", 'ON')
            elif msg == 'OFF':
                peripherals.controlrelays(5, 0)
                publish("d13", 'OFF')
            else:
                print('unknown:' + message.topic + ' message:' + msg)

        if message.topic == (config.MQTT_PATH + "/set/alert"):

            if msg == 'ON':
                peripherals.eg_object.alert = 1
                publish("alert", 'ON')
            elif msg == 'OFF':
                peripherals.eg_object.alert = 0
            else:
                print('unknown:' + message.topic + ' message:' + msg)

        if message.topic == (config.MQTT_PATH + "/set/max_backlight"):
            assert 0 < (int)(msg) < 32, 'value outside 1..31'
            peripherals.eg_object.max_backlight = (int)(msg)
            peripherals.controlbacklight((int)(msg))

        if message.topic == (config.MQTT_PATH + "/set/vent_pwm"):
            assert -1 < (int)(msg) < 256, 'value outside 0..255'
            peripherals.controlvent((int)(msg))

        if message.topic == (config.MQTT_PATH + "/set/set_temp"):
            assert 0 < (float)(msg) < 50, 'value outside 1..50'
            peripherals.eg_object.set_temp = (float)(msg)

        if message.topic == (config.MQTT_PATH + "/set/led"):
            value = msg.split(',')
            if len(value) == 3:
                peripherals.controlled(value)
예제 #2
0
파일: httpserver.py 프로젝트: schit/mySHPI
       def do_GET(self):
         
         try:

           if "?" in self.path:
             start_time = time.time()
             message = ''
             self.send_response(200)
             
             print(self.client_address[0],end=': ')

             for key, value in dict(urlparse.parse_qsl(self.path.split("?")[1], True)).items():


              if key == 'screenshot':
               self.send_header('Content-type','image/png')
               self.end_headers()
               byte_io = BytesIO()
               img = pi3d.util.Screenshot.screenshot()
               im = Image.frombuffer('RGB', (800, 480), img, 'raw', 'RGB', 0, 1)
               im.save(byte_io, format='PNG', quality=90)
               self.wfile.write(byte_io.getvalue())



              else:
               self.send_header('Content-type','text')
               self.end_headers()
               if key == 'lastmotion': # special treatment
                 message += '{}_date:{}_{:.1f}s_ago;'.format(
                         key,
                         time.strftime("%Y-%m-%d_%H:%M:%S", time.gmtime(peripherals.eg_object.lastmotion)), 
                         time.time() - peripherals.eg_object.lastmotion
                 )
               elif hasattr(peripherals.eg_object, key):
                 message += '{}:{};'.format(key, getattr(peripherals.eg_object, key))

                 if (value != ''):
                   try:                             #its better to split in different functions, to achieve easier compatibility with shpi lite
                     if key in ('backlight_level'):             
                       value = int(value) # variable int value
                       assert -1 < value < 32, 'value outside 0..31'
                       peripherals.controlbacklight(value)
                       
                     elif key in ('vent_pwm'):
                       value = int(value) # variable int value
                       assert -1 < value < 256, 'value outside 0..255'
                       peripherals.controlvent(value)

                     elif key in ('slide'):
                       value = int(value) # variable int value
                       assert -1 < value < len(config.slides), 'value outside 0..255'
                       peripherals.eg_object.slide = value


                       
                     elif key in ('led'):
                       value = value.split(',') # variable int value
                       peripherals.controlled(value)  

                     elif key in ('alert'):
                       peripherals.eg_object.alert = int(value)
                         


                     elif key in ('buzzer'):
                       value = int(value)
                       peripherals.controlrelays(4,value)  
  
                     else:
                      if  key.startswith('relais'):
                         channel = int(key[-1])
                         peripherals.controlrelays(channel,(int)(value))
                   except Exception as e:
                     message += 'Excepton:{}>{};'.format(key, e)
                   finally:
                     message +=  '{}>{};'.format(key, value)  #we should update eg_object here?

               self.wfile.write(bytes(message, "utf8"))
               self.connection.close()

             print(message)
             print("-- %s seconds --" % (time.time() - start_time))
             #self.wfile.write(bytes(message, "utf8"))
             #self.connection.close()
           else:
             self.send_response(404)
             self.connection.close()
         except Exception as e:
           print(e)
           self.send_response(400)
           self.connection.close()

         return
예제 #3
0
    def do_GET(self):

        try:

            if "?" in self.path:
                start_time = time.time()
                message = ''
                self.send_response(200)

                print(self.client_address[0])

                for key, value in dict(
                        urlparse.parse_qsl(self.path.split("?")[1],
                                           True)).items():

                    if key == 'screenshot':

                        self.send_header('Content-type', 'image/png')
                        self.end_headers()
                        os.popen('rm /media/ramdisk/screenshot.png')
                        time.sleep(0.01)
                        while (os.path.exists("/media/ramdisk/screenshot.png")
                               == False):
                            time.sleep(0.1)
                        # self.wfile.write(screenshot.getvalue())
                        with open('/media/ramdisk/screenshot.png',
                                  'rb') as content_file:
                            self.wfile.write(content_file.read())

                    else:
                        self.send_header('Content-type', 'text')
                        self.end_headers()
                        if key == 'lastmotion':  # special treatment
                            message += '{}_date:{}_{:.1f}s_ago;'.format(
                                key,
                                time.strftime(
                                    "%Y-%m-%d_%H:%M:%S",
                                    time.gmtime(
                                        peripherals.eg_object.lastmotion)),
                                time.time() - peripherals.eg_object.lastmotion)
                        elif key == 'all':
                            for subkey in peripherals.eg_object.__dict__:
                                message += '{}:{};'.format(
                                    subkey,
                                    getattr(peripherals.eg_object, subkey))

                        elif hasattr(peripherals.eg_object, key):
                            message += '{}:{};'.format(
                                key, getattr(peripherals.eg_object, key))

                            if (value != ''):
                                try:  # its better to split in different functions, to achieve easier compatibility with shpi lite
                                    if key in ('backlight_level'):
                                        # variable int value
                                        value = int(value)
                                        assert -1 < value < 32, 'value outside 0..31'
                                        peripherals.controlbacklight(value)

                                    elif key in ('vent_pwm'):
                                        # variable int value
                                        value = int(value)
                                        assert -1 < value < 256, 'value outside 0..255'
                                        peripherals.controlvent(value)

                                    elif key in ('slide'):
                                        # variable int value
                                        value = int(value)
                                        assert - \
                                            1 < value < len(
                                                config.slides), 'value outside 0..255'
                                        peripherals.eg_object.slide = value

                                    elif key in ('led'):
                                        # variable int value
                                        value = value.split(',')
                                        peripherals.controlled(value)

                                    elif key in ('alert'):
                                        peripherals.eg_object.alert = int(
                                            value)

                                    elif key in ('buzzer'):
                                        value = int(value)
                                        peripherals.controlrelays(4, value)

                                    else:
                                        if key.startswith('relais'):
                                            channel = int(key[-1])
                                            peripherals.controlrelays(
                                                channel, (int)(value))
                                except Exception as e:
                                    message += 'Excepton:{}>{};'.format(key, e)
                                finally:
                                    # we should update eg_object here?
                                    message += '{}>{};'.format(key, value)

                        self.wfile.write(bytes(message, "utf8"))
                        self.connection.close()

                print(message)
                print("-- %s seconds --" % (time.time() - start_time))
                #self.wfile.write(bytes(message, "utf8"))
                # self.connection.close()
            else:
                self.send_response(404)
                self.connection.close()
        except Exception as e:
            print(e)
            self.send_response(400)
            self.connection.close()

        return
예제 #4
0
파일: main.py 프로젝트: schit/mySHPI

    
    temperatures_str = 'N:{:.2f}:{:.2f}:{:.2f}:{:.2f}:{:.2f}:{:.2f}:{:.2f}:{:.2f}:{:.2f}'.format(
      peripherals.eg_object.act_temp, peripherals.eg_object.gputemp, peripherals.eg_object.cputemp, peripherals.eg_object.atmega_temp,
      sht_temp, bmp280_temp, peripherals.eg_object.mlxamb, peripherals.eg_object.mlxobj,(0.0))

    start_new_thread(rrdtool.update,('temperatures.rrd', temperatures_str))

    print(temperatures_str)


    if config.show_airquality:
        redvalue = 255 if peripherals.eg_object.a4 > 600 else int(0.03 * peripherals.eg_object.a4)
        greenvalue = 0 if peripherals.eg_object.a4 > 400 else int(0.02*(400 - peripherals.eg_object.a4))
        peripherals.controlled([redvalue,greenvalue,0])

    if config.startmqttclient: mqttclient.publishall()
    
    textchange = True



  if not config.subslide:

    if now > nexttm and not peripherals.touched():                                     # change background
      nexttm = now + config.TMDELAY
      a = 0.0
      sbg = sfg
      sbg.positionZ(5)
      pic_num = (pic_num + 1) % nFi
예제 #5
0
def sensor_thread():
    global textchange, a, sbg, sfg, now
    last_backlight_level = 0
    iFiles, nFi = get_files()
    pic_num = nFi - 1
    sfg = graphics.tex_load(iFiles[pic_num])
    nextsensorcheck = 0
    everysecond = 0
    nexttm = 0

    while True:

        if now > nexttm:  # change background
            nexttm = now + config.TMDELAY

            sbg = sfg
            sbg.positionZ(5)
            pic_num = (pic_num + 1) % nFi
            sfg = graphics.tex_load(iFiles[pic_num])
            a = 0

        if peripherals.eg_object.alert:
            peripherals.alert()
        elif config.subslide == 'alert':  # alert == 0
            peripherals.alert(0)
            config.subslide = None
            if config.startmqttclient:
                mqttclient.publish('alert', 'off')

        if config.backlight_auto:

            if now < peripherals.eg_object.lastmotion + config.backlight_auto:
                peripherals.eg_object.backlight_level = peripherals.eg_object.max_backlight

            else:
                peripherals.eg_object.backlight_level = 0

        if peripherals.eg_object.backlight_level != last_backlight_level:
            print('set backlight:' +
                  str(peripherals.eg_object.backlight_level))
            peripherals.controlbacklight(peripherals.eg_object.backlight_level)
            last_backlight_level = peripherals.eg_object.backlight_level

        if config.starthttpserver:
            littleserver.handle_request()
        else:
            time.sleep(0.1)

        if config.startmqttclient:
            mqttclient.publishall()

        if (now > everysecond):
            peripherals.get_infrared()
            everysecond = now + config.INFRARED_TM

        if (now > nextsensorcheck):

            peripherals.get_sensors()
            nextsensorcheck = now + config.SENSOR_TM

            if config.coolingrelay and config.coolingrelay == config.heatingrelay:
                peripherals.coolingheating()
            else:
                if config.coolingrelay:
                    peripherals.cooling()
                if config.heatingrelay:
                    peripherals.heating()

            peripherals.get_status()
            textchange = True
            if hasattr(peripherals.eg_object, 'bmp280_temp'):
                bmp280_temp = peripherals.eg_object.bmp280_temp
            else:
                bmp280_temp = 0

            if hasattr(peripherals.eg_object, 'sht_temp'):
                sht_temp = peripherals.eg_object.sht_temp
            else:
                sht_temp = 0
            if peripherals.eg_object.motion:
                motion = 1
            else:
                motion = 0

            temperatures_str = 'N:{:.2f}:{:.2f}:{:.2f}:{:.2f}:{:.2f}:{:.2f}:{:.2f}:{:.2f}:{:.2f}:{:d}:{:d}:{:d}:{:.2f}:{:d}'.format(
                peripherals.eg_object.act_temp, peripherals.eg_object.gputemp,
                peripherals.eg_object.cputemp,
                peripherals.eg_object.atmega_temp, sht_temp, bmp280_temp,
                peripherals.eg_object.mlxamb, peripherals.eg_object.mlxobj,
                (0.0),
                getattr(peripherals.eg_object,
                        'relais' + (str)(config.heatingrelay)),
                getattr(peripherals.eg_object,
                        'relais' + (str)(config.coolingrelay)), motion,
                peripherals.eg_object.humidity, peripherals.eg_object.a4)

            print(temperatures_str)
            rrdtool.update(str('temperatures.rrd'), str(temperatures_str))

            if config.show_airquality:
                redvalue = 255 if peripherals.eg_object.a4 > 600 else int(
                    0.03 * peripherals.eg_object.a4)
                greenvalue = 0 if peripherals.eg_object.a4 > 400 else int(
                    0.02 * (400 - peripherals.eg_object.a4))
                peripherals.controlled([redvalue, greenvalue, 0])