Ejemplo n.º 1
0
def get_station_name():
    hardware_parameters = database.get_hardware_parameters()
    mac_address = utils.get_mac_address('-')

    idx = hardware_parameters['macAddress'].index(mac_address)
    station_name = hardware_parameters['stationName'][idx]

    return station_name
Ejemplo n.º 2
0
    def send_handshake(self):
        local_ip = commands.getoutput("hostname -I")

        message = {
            'bot_name': self.bot_name,
            'bot_roles': self.bot_roles,
            'mac': get_mac_address(),
            'handshake': True,
            'subscriptions': settings['subscriptions'],
            'sensors': SENSORS,
            'local_ip': local_ip
        }
        print "Sending handshake"
        self.send(message)
Ejemplo n.º 3
0
    def opened(self):
        print "Connection to ardh is open"
        message = {'bot_name':self.bot_name, 
                   'bot_roles':self.bot_roles,
                   'mac':get_mac_address(),
                   'handshake':True,
                   'subscriptions':settings['subscriptions']
                   }


        self.send(message)

        if ["jjbot", "grovebot"] and settings["bot_packages"]:
            print "Registering IO Loop callback"
            sensors = tornado.ioloop.PeriodicCallback(self.loopCallback, LOOP_CALLBACK_DT*1000)
            sensors.start()
Ejemplo n.º 4
0
 def get_mac_address(self):
     return get_mac_address() 
Ejemplo n.º 5
0
def send_power_cycle_email(station_parameters):

    # Get the hostname
    hostname = socket.gethostname()

    # Get the MAC address
    mac_address = utils.get_mac_address('-')

    # Get the IP address
    ip_address = utils.get_ip_address()
    if ip_address is None:
        ip_address = 'n/a'

    # Get the current universal coordinated time (UTC)
    iso8601_time_string = clock.iso8601_time_string_using_computer_clock()

    # Form the message
    message = 'From: {0}\n'.format(station_parameters['emailSender'])
    if type(station_parameters['emailReceivers']) is list:
        r = str(station_parameters['emailReceivers'])[1:-1]
        r = r.replace("'", "").replace('"', '')
        message += 'To: {0}\n'.format(r)
    else:
        message += 'To: {0}\n'.format(station_parameters['emailReceivers'])
    message += 'Subject: *** IMPORTANT *** Camera Power Cycle Occurred '
    message += '({0}) '.format(mac_address)
    message += '[{0}]\n'.format(station_parameters['stationName'])
    message += '\n'
    message += 'Hostname:  {0}\n'.format(hostname)
    message += 'Station name:  {0}\n'.format(station_parameters['stationName'])
    message += 'MAC:  {0}\n'.format(mac_address)
    message += 'IP address:  {0}\n'.format(ip_address)
    message += '\n'
    message += 'Time:  {0}\n'.format(iso8601_time_string)
    message += '\n'
    message += 'A power cycle was just completed on the camera attached to '
    message += 'this station.  You should check the operations log to make '
    message += 'sure that normal operations have resumed.\n'
    message += '\n'
    message += 'If normal operations have not resumed, you may want to '
    message += 'consider:\n'
    message += '\n'
    message += '   1) Terminating and restarting the collection script\n'
    message += '   2) Power cycling the camera again manually\n'
    message += '   3) Rebooting the controlling computer\n'

    # Send the message
    smtp = smtplib.SMTP()
    try:
        smtp.connect(station_parameters['smtpServer'])
    except socket.gaierror:
        msg = '*** ERROR *** SMTP server address is invalid or could not be '
        msg += 'resolved'
        msg += '\n'
        sys.stderr.write(msg)
        sys.stderr.flush()
        sys.exit()
    except:
        msg = '*** WARNING *** Unable to connect to SMTP server to send'
        msg += 'power cycle message'
        msg += '\n'
        msg += '... aborting attempt'
        msg += '\n'
        msg += '\n'
        sys.stdout.write(msg)
        sys.stdout.flush()
        return

    try:
        smtp.sendmail(station_parameters['emailSender'],
                      station_parameters['emailReceivers'], message)
    except smtplib.SMTPException:
        msg = '*** WARNING *** Unable to send power cycle message'
        msg += '\n'
        msg += '... aborting attempt'
        msg += '\n'
        msg += '\n'
        sys.stdout.write(msg)
        sys.stdout.flush()
        return
Ejemplo n.º 6
0
        else:
            station_parameters['allowPowerCycle'] = False

    # Convert e-mail receivers from a string to a list
    if isinstance(station_parameters['emailReceivers'], str):
        receivers = station_parameters['emailReceivers']
        station_parameters['emailReceivers'] = receivers.split('|')

    # Convert SMS receivers from a string to a list
    if isinstance(station_parameters['smsReceivers'], str):
        receivers = station_parameters['smsReceivers']
        station_parameters['smsReceivers'] = receivers.split('|')

    # Organize hardware information into a device-specific dictionary
    hardware = {}
    mac_address = utils.get_mac_address('-')
    try:
        index = hardware_parameters['macAddress'].index(mac_address)
        hardware['station_name'] = hardware_parameters['stationName'][index]
        hardware['interface_name'] = hardware_parameters['interfaceName'][
            index]
        hardware['mac_address'] = mac_address
        hardware['ipv4_address'] = hardware_parameters['ipv4Address'][index]
        hardware['dns_name'] = hardware_parameters['dnsName'][index]
        hardware['port_number'] = hardware_parameters['portNumber'][index]
        hardware['phone_number'] = hardware_parameters['phoneNumber'][index]
    except ValueError:
        hardware = {}
        hardware['station_name'] = None
        hardware['interface_name'] = None
        hardware['mac_address'] = mac_address
Ejemplo n.º 7
0
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((settings.http.bind_address, settings.http.port))
            print "Server already running, exiting."
            sys.exit(2)
        except socket.error, msg:
            pass
        log.info("Socket free.")

        uzbl = None
        if not settings.staging:
            # Get the browser going
            uzbl = browser.Browser()
            p = playlist.Player(uzbl, 'playlist.json')
            log.info("Starting player thread")
            p.start()

            if hasattr(settings, 'server_url'):
                b = beacon.Beacon(utils.get_mac_address(settings.interface),
                                  uzbl)
                log.info("Starting beacon thread")
                b.start()
            else:
                log.info("No server configured, operating in standalone mode.")

    log.info("Serving requests.")
    bottle.run(port=settings.http.port,
               host=settings.http.bind_address,
               debug=settings.debug,
               reloader=settings.debug)
Ejemplo n.º 8
0
            sys.exit(2)
        except socket.error, msg:
            pass
        log.info("Socket free.")

        if ip_address or settings.staging:
            uzbl = None
            if not settings.staging:
                # Get the browser going
                uzbl = browser.Browser()
                p = playlist.Player(uzbl, 'playlist.json')
                log.info("Starting player thread")
                p.start()

                if hasattr(settings, 'server_url'):
                    b = beacon.Beacon( utils.get_mac_address(settings.interface), ip_address, uzbl)
                    log.info("Starting beacon thread")
                    b.start()
                else:
                    log.info("No server configured, operating in standalone mode.")
        else:
            # Signal for help and stay put. There's no point in debugging the LAN ourselves.
            uzbl = browser.Browser()
            uzbl.do(settings.uzbl.uri % (local_uri + '/nonet'))
            log.error("Failsafe mode")

    log.info("Serving requests.")
    bottle.run(
        port     = settings.http.port, 
        host     = settings.http.bind_address, 
        debug    = settings.debug,
Ejemplo n.º 9
0
def send_health_email(station_parameters,
                      station_parameters_pickup_successful=False,
                      hourly_parameters_pickup_successful=False,
                      hardware_parameters_pickup_successful=False,
                      upload_successful=False,
                      files_uploaded=0,
                      captures_failed=0):

   # Get the hostname
   hostname = socket.gethostname()

   # Get the MAC address
   mac_address = utils.get_mac_address('-')

   # Get the IP address
   ip_address = utils.get_ip_address()
   if ip_address is None:
      ip_address = 'n/a'

   # Get the sunrise and sunset times for the current day
   iso8601_time_string = clock.iso8601_time_string_using_computer_clock()
   sunrise, sunset = clock.sunrise_sunset(iso8601_time_string,
                                          station_parameters['longitude'],
                                          station_parameters['latitude'])

   # Get the storage statistics
   images_directory = \
      os.path.join(station_parameters['localDirectory'], 'images')
   filenames = utils.get_file_listing(images_directory)
   bytes_used = 0
   for filename in filenames:
      bytes_used += os.path.getsize(filename)

   # Get the voltage(s)
   fieldNames = \
      ['voltmeter1Label',
       'voltmeter2Label',
       'voltmeter3Label',
       'voltmeter4Label',
       'voltmeter5Label',
       'voltmeter6Label',
       'voltmeter7Label',
       'voltmeter8Label']
   voltmeterLabels = []
   voltages = []
   for fieldName in fieldNames:
      if len(station_parameters[fieldName]):
         voltmeterLabels.append(station_parameters[fieldName])
      else:
         voltmeterLabels.append(None)
      voltmeter = battery.Voltmeter(fieldNames.index(fieldName))
      voltages.append(voltmeter.read(samples=16))
      voltmeter.close()

   # Get the enclosure's interior environmental paramaters
   readings = sensors.temperature_humidity(temperature_units='f')
   if readings:
      temperature, humidity = readings
   else:
      temperature = None
      humidity = None

   packet_loss_percentage = \
      utils.packet_loss_percentage('pegasus.cis.rit.edu', 10)

   # Form the message
   message = 'From: {0}\n'.format(station_parameters['emailSender'])
   if type(station_parameters['emailReceivers']) is list:
      r = str(station_parameters['emailReceivers'])[1:-1]
      r = r.replace("'", "").replace('"', '')
      message += 'To: {0}\n'.format(r)
   else:
      message += 'To: {0}\n'.format(station_parameters['emailReceivers'])
   message += 'Subject: Daily Health Message '
   message += '({0}) '.format(mac_address)
   message += '[{0}]\n'.format(station_parameters['stationName'])
   message += '\n'
   message += 'Hostname:  {0}\n'.format(hostname)
   message += 'Station name:  {0}\n'.format(station_parameters['stationName'])
   message += 'MAC:  {0}\n'.format(mac_address)
   message += 'IP address:  {0}\n'.format(ip_address)
   message += '\n'
   message += 'Time:  {0}\n'.format(iso8601_time_string)
   message += 'Sunrise:  {0}\n'.format(sunrise)
   message += 'Sunset:  {0}\n'.format(sunset)
   message += '\n'
   if any(voltmeterLabels):
      for voltmeterLabel in voltmeterLabels:
         if voltmeterLabel:
            message += voltmeterLabel
            message += ': '
            v = voltages[voltmeterLabels.index(voltmeterLabel)]
            message += '{0:.2f}'.format(v) if v else '0.00'
            message += '\n'
      message += '\n'
   message += station_parameters['temperatureLabel']
   message += ':  '
   message += '{0:.1f}\n'.format(temperature) if temperature else 'n/a\n'
   message += station_parameters['humidityLabel']
   message += ':  '
   message += '{0:.1f}\n'.format(humidity) if humidity else 'n/a\n'
   message += '\n'
   message += 'Current packet loss: {0}%\n'.format(packet_loss_percentage)
   if station_parameters['updateHour'] >= 0:
      message += '\n'
      message += 'Most recent station parameters update:  '
      message += \
         'SUCCESS\n' if station_parameters_pickup_successful else 'FAILED\n'
      message += 'Most recent hourly parameters update:  '
      message += \
         'SUCCESS\n' if hourly_parameters_pickup_successful else 'FAILED\n'
      message += 'Most recent hardware parameters update:  '
      message += \
         'SUCCESS\n' if hardware_parameters_pickup_successful else 'FAILED\n'
   if station_parameters['uploadHour'] >= 0:
      message += '\n'
      message += 'Most recent file upload attempt:  '
      message += \
         'SUCCESS ({0} files uploaded)\n'.format(files_uploaded) \
         if upload_successful else 'FAILED\n'
      message += '\n'
      message += 'Number of images currently held on station\'s local storage: '
      message += '{0:,}\n'.format(len(filenames))
      message += 'Local storage currently used:  '
      message += '{0:,} [bytes]\n'.format(bytes_used)
   message += '\n'
   message += 'Number of image captures that were unsuccessful: '
   message += '{0}\n'.format(captures_failed)

   # Send the message
   smtp = smtplib.SMTP()
   try:
      smtp.connect(station_parameters['smtpServer'])
   except socket.gaierror:
      msg = '*** ERROR *** SMTP server address is invalid or could not be '
      msg += 'resolved'
      msg += '\n'
      sys.stderr.write(msg)
      sys.stderr.flush()
      sys.exit()
   except:
      msg = '*** WARNING *** Unable to connect to SMTP server to send'
      msg += 'daily health message'
      msg += '\n'
      msg += '... aborting attempt'
      msg += '\n'
      msg += '\n'
      sys.stdout.write(msg)
      sys.stdout.flush()
      return

   try:
      smtp.sendmail(station_parameters['emailSender'],
                    station_parameters['emailReceivers'],
                    message)
   except smtplib.SMTPException:
      msg = '*** WARNING *** Unable to send daily health message'
      msg += '\n'
      msg += '... aborting attempt'
      msg += '\n'
      msg += '\n'
      sys.stdout.write(msg)
      sys.stdout.flush()
      return
Ejemplo n.º 10
0
            sys.exit(2)
        except socket.error, msg:
            pass
        log.info("Socket free.")

        if ip_address or config.staging:
            uzbl = None
            if not config.staging:
                # Get the browser going
                uzbl = browser.Browser(config)
                p = playlist.Player(config, uzbl, 'playlist.json')
                log.info("Starting player thread")
                p.start()

                if hasattr(config, 'server_url'):
                    b = beacon.Beacon(config, utils.get_mac_address(config.interface), ip_address, uzbl)
                    log.info("Starting beacon thread")
                    b.start()
                else:
                    log.info("No server configured, operating in standalone mode.")
        else:
            # Signal for help and stay put. There's no point in debugging the LAN ourselves.
            uzbl = browser.Browser(config)
            uzbl.do(config.uzbl.uri % (local_uri + '/nonet'))
            log.error("Failsafe mode")

    log.info("Serving requests.")
    bottle.run(
        port     = config.http.port, 
        host     = config.http.bind_address, 
        debug    = config.debug,