Esempio n. 1
0
    def post(self):
        global VerifyLinkIDLength
        with db.getCur() as cur:
            email = self.get_argument("email", None)
            cur.execute("SELECT Id FROM Users WHERE Email = ?", (email, ))
            row = cur.fetchone()
            if row is not None:
                code = util.randString(VerifyLinkIDLength)
                cur.execute(
                    "INSERT INTO ResetLinks(Id, User, Expires) "
                    "VALUES (?, ?, ?)",
                    (code, row[0], expiration_date().isoformat()))

                util.sendEmail(
                    email, "Your {0} Account".format(settings.WEBSITENAME), """
<p>Here's the link to reset your {websitename} account password.<br />
Click <a href="{hostprefix}/reset/{code}">this link</a> to reset your password,
or copy and paste the following into your URL bar:<br />
{hostprefix}/reset/{code} </p>
""".format(websitename=settings.WEBSITENAME,
                hostprefix=this_server(self.request),
                code=code))
                self.render("message.html",
                            message="Your password reset link has been sent")
            else:
                self.render(
                    "message.html",
                    message="No account found associated with this email",
                    email=email)
Esempio n. 2
0
    def post(self):
        global VerifyLinkIDLength
        email = self.get_argument('email', None)
        if not db.valid['email'].match(email):
            self.render("setup.html",
                        message="Please enter a valid email address.")
        else:
            with db.getCur() as cur:
                code = util.randString(VerifyLinkIDLength)
                cur.execute(
                    "INSERT INTO VerifyLinks (Id, Email, Expires) "
                    "VALUES (?, LOWER(?), ?)",
                    (code, email, expiration_date().isoformat()))

                if len(settings.EMAILPASSWORD) > 0:
                    util.sendEmail(
                        email, "Your {0} Account".format(settings.WEBSITENAME),
                        format_invite(settings.WEBSITENAME,
                                      this_server(self.request), code))

                    self.render(
                        "message.html",
                        message="Invite sent. It will expire in {0} days.".
                        format(settings.LINKVALIDDAYS),
                        title="Invite")
                else:
                    self.redirect("{}/verify/{}".format(
                        settings.PROXYPREFIX.rstrip('/'), code))
Esempio n. 3
0
def accounts_new():
    name = request.params.get('name')
    email = request.params.get('email')
    #TODO: Check phone format
    phone = request.params.get('phone')
    try:
        privilege_id = int(request.params.get('privilege_id'))
    except ValueError:
        abort(400, 'Invalid privilege_id')
    if privilege_id > request.user.privilege_id:
        unauthorized()
    #TODO: Check for lengths, instead of relying on db?
    password = generatePassword()
    seed = generatePassword() + generatePassword()
    passwordHash = hashlib.sha1(seed + password).hexdigest()
    rowData = {
        "name": name,
        "email": email,
        "password": passwordHash,
        "seed": seed,
        "privilege_id": privilege_id
    }
    if (phone):
        rowData["phone"] = phone
    id = util.insertRow("account", rowData)

    #TODO: Send new account email
    util.sendEmail(
        email, '*****@*****.**', 'Welcome to Isadore',
        "Welcome to the Isadore system. You can login by going to https://" +
        request.urlparts[1] + "\n\n" +
        "To login use the following\n\nEmail:   " + email + "\nPassword:   "******"\n\n")
    return {'xlink': ['/resources/accounts/' + str(id)]}
Esempio n. 4
0
 def createPickUp(self):
     while True:
         try:
             self.sendPickUpReq(2)
             status = self.network.getStatus()
             if status >= 200 and status < 400:
                 self.p_trigger.emit(self.info.phoneNumber,u'预定成功,查询邮件确认')
                 self.c_trigge.emit(2)
                 util.sendEmail(2)
                 break
             else:
                 self.sendPickUpReq(1)
                 status = self.network.getStatus()
                 if status >=200 and status < 400:
                     self.p_trigger.emit(self.info.phoneNumber,u'预定成功,查询邮件确认')
                     self.c_trigge.emit(1)
                     util.sendEmail(1)
                 else:
                     try:
                         isError, errorMessage = self.getPickUpError()
                         if not isError:
                             self.p_trigger.emit(self.info.phoneNumber,(unicode(errorMessage)))
                     except ValueError,e:
                         self.p_trigger.emit(self.info.phoneNumber,u'预定失败')
                 break
         except ServerNotFound,e:
             self.p_trigger.emit(self.info.phoneNumber,u'服务器忙,努力中............')
             continue
Esempio n. 5
0
    def sendAlarmNotice(self, alarm_id, alarmMSG):
        cur = self.conn.cursor()
        sql = "SELECT account.email FROM account, alarm WHERE account.id=alarm.account_id and alarm.id = %s AND alarm.id IN (SELECT alarm_id FROM alarm_contact WHERE alarm_contact_type_id = %s)"
        cur.execute(sql, (alarm_id, self.ALARM_CONTACT_TYPE_EMAIL))
        row = cur.fetchone()
        email = None
        if (row):
            email = row[0]

        sql = "SELECT account.phone FROM account, alarm WHERE account.id=alarm.account_id and alarm.id = %s AND alarm.id IN (SELECT alarm_id FROM alarm_contact WHERE alarm_contact_type_id = %s)"
        cur.execute(sql, (alarm_id, self.ALARM_CONTACT_TYPE_SMS))
        row = cur.fetchone()
        sms = None
        if (row):
            sms = row[0]

        if (email):
            amsg = self.msg % (alarmMSG, util.datetimeToReadable(self.now))
            logging.debug("sendEmail to " + email + ": " + amsg)
            util.sendEmail(email, "*****@*****.**", self.subject,
                           amsg)
        if (sms):
            amsg = self.shortMsg % (alarmMSG, util.datetimeToReadable(
                self.now))
            #Send SMS
            logging.debug("sendSMS to " + sms + ": " + amsg)
            pass
Esempio n. 6
0
    def post(self):
        email = self.get_argument('email', None)
        if not re.match("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]+$", email, flags = re.IGNORECASE):
            self.render("invite.html", message = "Please enter a valid email address.")
        else:
            with db.getCur() as cur:
                cur.execute("SELECT Email from Users where Email = ?", (email,))
                try:
                    existing = cur.fetchone()[0]
                    self.render("message.html",
                                message = "Account for {0} already exists.".format(
                                    email),
                                title="Duplicate Account")
                    return
                except:
                    pass
                code = util.randString(32)
                cur.execute("INSERT INTO VerifyLinks (Id, Email, Expires) "
                            "VALUES (?, LOWER(?), ?)",
                            (code, email, expiration_date().isoformat()))

            util.sendEmail(email, "Your {0} Account".format(settings.CLUBNAME),
                           format_invite(settings.CLUBNAME, self.request.host,
                                         code))

            self.render("message.html",
                        message = "Invite sent. It will expire in {0} days."
                        .format(settings.LINKVALIDDAYS),
                        title = "Invite")
def sendPictureEmail(source, delay):

    print("sendPictureEmail source:%s" % source)
    time.sleep(delay)

    util.sendEmail("test", "picture from ProjectCuracao", "Afternoon Picture",
                   conf.notifyAddress, conf.fromAddress,
                   "/home/pi/RasPiConnectServer/static/picamera.jpg")
Esempio n. 8
0
def writeFileAndEmailWhenDone(args):
    fileHandle = fp.getFileHandle(args.shPath, 'w');
    fileHandle.write(" ".join(args.args));
    fileHandle.close();
    os.system("bash "+args.shPath);
    util.sendEmail(args.email, '*****@*****.**', "Done "+args.shPath, "");
    if (args.dontRm == False):
        os.system("rm "+args.shPath);
def sendPictureEmail(source,delay):

	print("sendPictureEmail source:%s" % source)
	time.sleep(delay)


	

	util.sendEmail("test", "picture from ProjectCuracao", "Afternoon Picture", conf.notifyAddress, conf.fromAddress, "/home/pi/RasPiConnectServer/static/picamera.jpg");
Esempio n. 10
0
def kickoffWhenDone(args):
    fileHandle = fp.getFileHandle(args.shPath, 'w');
    fileHandle.write(" ".join(args.args));
    fileHandle.close();
    outFile = args.shPath+".out";
    os.system("sh "+args.shPath+" >"+outFile+" 2>&1");
    util.sendEmail(args.email, '*****@*****.**', "Done "+args.shPath, "");
    if (args.dontRm == False):
        os.system("rm "+args.shPath);
        os.system("rm "+outFile);
Esempio n. 11
0
    def onNewUser(self, user_model, coupon_model, user_id):
        # send email to new user
        user = user_model.getUserById(user_id)
        if user:
            util.sendEmail([user.email],
                           util.getWelcomEmailContent(user.username))

        # add coupon
        coupon_id = const.NEW_USER_COUPON_ID
        coupon_model.addCoupon(user_id, coupon_id, 1)
Esempio n. 12
0
def email(email_address):
    with db.getCur() as cur:
        code = util.randString(32)
        cur.execute(
            "INSERT INTO VerifyLinks (Id, Email, Expires) VALUES (?, ?, ?)",
            (code, email_address,
             (datetime.date.today() + datetime.timedelta(days=7)).isoformat()))

        util.sendEmail(
            email_address, "Your {0} Account".format(settings.CLUBNAME),
            login.format_invite(settings.CLUBNAME, settings.WEBHOST, code))
Esempio n. 13
0
File: main.py Progetto: lhysrc/utils
def auto_check_in():
    # sleep_secs = randint(0, 1800)
    # log.info(u'将在%d秒后进行虾米签到。' % sleep_secs)
    # time.sleep(sleep_secs)    
    try:
        x = xiami()
        ret = x.check_in()
        if ret:
            util.sendEmail('*****@*****.**', u'虾米签到失败', ret)
    except Exception, ex:
        util.sendEmail('*****@*****.**', u'虾米签到失败', ex)
Esempio n. 14
0
def test():
    """
    Test any new changes to the DNSMasq conf files.

    If an error is thrown - the test failed - then the error is logged
    and the master exits.
    """
    try:
        # Executes the shell command to test the DNSMasq conf files.
        util.execute("dnsmasq --test")
        log.debug("Config file test passed.")
        util.execute("systemctl restart dnsmasq")
        log.debug("Restarting DNSMasq")
        util.execute("systemctl is-active dnsmasq")
        log.debug("DNSMasq restarted.")

        for record in test_records:
            cmd = "dig @localhost " + record + " -p " + dnsmasq_port + " +short"
            log.debug("Executing: " + cmd)
            start = time.time()
            ret = util.execute(cmd)
            end = time.time()
            passed = end - start
            log.debug("Returned: \n" + ret.strip())
            log.debug("Processed in " + str(passed) + " seconds.")
            if ret == "":
                raise RuntimeError("Dig at %r failed: No result" % (record))
            if passed > 2:
                raise RuntimeError("Dig at %r failed: Long return time" %
                                   (record))
    except:
        # Log the error
        error = 'Failure: ' + str(sys.exc_info()[0])
        log.critical(error)
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        tracebk = ''.join('!! ' + line for line in lines)
        log.critical(tracebk)
        try:
            fl = re.match('.*?(/.*)\'$', lines[len(lines) - 1]).group(1)
            lineNumber = int(
                re.match('.*?line ([0-9]+) of',
                         lines[len(lines) - 1]).group(1))
            line = communicator.getLineFromFile(lineNumber - 1, fl)
            fl_info = fl + " at line " + str(lineNumber) + ":\n\t" + line
            log.critical(fl_info)
        except:
            fl_info = ""
        util.sendEmail(
            receivers, "[copycat] CRITICAL -- copycat-master.py", email_sender,
            emailer.getEmailBody(error + "\n" + tracebk + "\n\n" + fl_info))
        # Exit
        raise SystemExit(1)
Esempio n. 15
0
    def post(self):
        with db.getCur() as cur:
            email = self.get_argument("email", None)
            cur.execute("SELECT Id FROM Users WHERE Email = ?", (email,))
            row = cur.fetchone()
            if row is not None:
                code = util.randString(32)
                cur.execute("INSERT INTO ResetLinks(Id, User, Expires) VALUES (?, ?, ?)", (code, row[0], (datetime.date.today() + datetime.timedelta(days=7)).isoformat()))

                util.sendEmail(email, "Your SeattleMahjong Account",
                    "<p>Here's the link to reset your SeattleMahjong account password\n<br />\
                    Click <a href=\"http://" +  self.request.host + "/reset/" + code + "\">this</a> link to reset your password or copy and paste the following into your URL bar:<br />http://" +  self.request.host + "/reset/" + code + "</p>\n")
                self.render("message.html", message = "Your password reset link has been sent")
            else:
                self.render("message.html", message = "No accounts found associated with this email", email = email)
Esempio n. 16
0
    def post(self):
        email = self.get_argument('email', None)
        if not re.match("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]+$", email, flags = re.IGNORECASE):
            self.render("invite.html", message = "Please enter a valid email address.")
        else:
            with db.getCur() as cur:
                code = util.randString(32)
                cur.execute("INSERT INTO VerifyLinks (Id, Email, Expires) VALUES (?, LOWER(?), ?)", (code, email, (datetime.date.today() + datetime.timedelta(days=7)).isoformat()))

            util.sendEmail(email, "Your SeattleMahjong Account",
                    "<p>You've been invited to SeattleMahjong\n<br />\
                    Click <a href=\"http://" +  self.request.host + "/verify/" + code + "\">this</a> link to accept the invite and register an account or copy and paste the following into your URL bar:<br />http://" +  self.request.host + "/verify/" + code + "</p>\n" +
                    "<p>If you believe you received this email in error, it can be safely ignored. It is likely a user simply entered your email by mistake.</p>")

            self.render("message.html", message = "Invite sent. It will expire in 7 days.", title = "Invite")
Esempio n. 17
0
def fromDB(db_params, full):
    """Load information from Database."""
    try:
        return communicator.fromDB(db_params, full)
    except:
        # Log the error
        error = 'Failure: ' + str(sys.exc_info()[0])
        log.critical(error)
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        tracebk = ''.join('!! ' + line for line in lines)
        log.critical(tracebk)
        util.sendEmail(receivers, "[copycat] CRITICAL -- communicator.py",
                       email_sender,
                       emailer.getEmailBody(error + "\n" + tracebk))
        # Exit
        raise SystemExit(1)
Esempio n. 18
0
    def post(self):
        email = self.get_argument('email', None)
        if not re.match("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]+$", email, flags = re.IGNORECASE):
            self.render("setup.html", message = "Please enter a valid email address.")
        else:
            with db.getCur() as cur:
                code = util.randString(32)
                cur.execute("INSERT INTO VerifyLinks (Id, Email, Expires) "
                            "VALUES (?, LOWER(?), ?)",
                            (code, email, expiration_date().isoformat()))

            util.sendEmail(email, "Your {0} Account".format(settings.CLUBNAME),
                           format_invite(settings.CLUBNAME, self.request.host,
                                         code))

            self.render("message.html",
                        message = "Invite sent. It will expire in {0} days."
                        .format(settings.LINKVALIDDAYS),
                        title = "Invite")
Esempio n. 19
0
def accounts_recover():
    email = request.params.get('email', None)
    if (not email):
        abort(400, 'Email parameter not given.')
    user = util.getAccountByEmail(email)
    #TODO: See if recovery has been tried lately and refuse new one if so?
    if (not user):
        abort(400, 'Email does not exist.')

    recovery_hash = hashlib.sha1(generatePassword() + user.email).hexdigest()
    while (len(
            util.getRowsFromTable(table="account",
                                  columns="id",
                                  extraWhere="recovery_hash = %s",
                                  extraArgs=(recovery_hash, ),
                                  checkEnabled=True)) > 0):
        recovery_hash = hashlib.sha1(generatePassword() +
                                     user.email).hexdigest()
    util.updateRowById("account", user.id, {'recovery_hash': recovery_hash})
    message = """%s:
    
A request has been sent to reset the password to your Isadore account. If you did not intend to reset your password you may ignore this message. To continue the reset process follow the instructions below:

Do one of the following:
  1) Goto the following:
    https://%s/isadore/s/login.html?c=%s#fs2
OR
  2) Type in the reset code in the form at:
    https://%s/isadore/s/login.html#fs2
    Using the code:
     %s


After 24 hours the reset code will expire and will have to send a new reset request if you wish to reset your password.\n\n""" % \
    (user.name, request.urlparts[1], recovery_hash, request.urlparts[1], recovery_hash)

    #    logging.debug(message)
    util.sendEmail(user.email, '*****@*****.**',
                   'Isadore Password Recovery', message)
    return HTTPResponse(output="Recovery Email Sent", status=204)
Esempio n. 20
0
    def sendGlobalNotices(self, short_name, alarm_type_id, event_time, conn):
        cur = conn.cursor()
        sql = """SELECT DISTINCT account.email FROM account, alarm WHERE account.id=alarm.account_id AND
            account.enabled_p AND alarm.alarm_type_id = %s AND alarm.id IN (SELECT alarm_id from alarm_contact WHERE
            alarm_contact_type_id = %s)"""
        cur.execute(sql,
                    (self.ALARM_TYPE_MID_DOWN, self.ALARM_CONTACT_TYPE_EMAIL))
        emails = []
        for row in cur:
            emails.append(row[0])
        sql = """SELECT DISTINCT account.phone FROM account, alarm WHERE account.id=alarm.account_id AND
            account.enabled_p AND alarm.alarm_type_id = %s AND alarm.id IN (SELECT alarm_id from alarm_contact WHERE
            alarm_contact_type_id = %s)"""
        cur.execute(sql,
                    (self.ALARM_TYPE_MID_DOWN, self.ALARM_CONTACT_TYPE_SMS))
        sms = []
        for row in cur:
            sms.append(row[0])
        if alarm_type_id == self.ALARM_TYPE_MID_DOWN:
            msg = short_name + "'s MID has not communicated in a while, detected on " + \
                util.datetimeToReadableWithTZ(event_time, self.tz)
            if emails:
                for email in emails:
                    try:
                        logging.debug("sendEmail to " + email + ": " + msg)
                        util.sendEmail(email, "*****@*****.**",
                                       "Isadore Alarm: MID Down", msg)
                    except:
                        logging.error(traceback.format_exc())
            if sms:
                logging.debug("sendSMS to " + str(sms) + ": " + msg)
                for s in sms:
                    try:
                        # alerts.send_SMS(sms, msg)
                        logging.debug("sendSMS to " + str(s) + ": " + msg)
                        util.sendTxt(s, msg)
                    except:
                        logging.error(traceback.format_exc())

        cur.close()
Esempio n. 21
0
def contact():
    name = request.params.get('name', None)
    email = request.params.get('email', None)
    subject = request.params.get('subject', None)
    message = request.params.get('message', None)

    if (not message):
        abort(400, 'Missing message.')

    realMessage = ''
    realMessage += 'Account Name<Email>: '
    realMessage += request.user.name + "<" + request.user.email + ">\n"
    realMessage += 'Form Name<Email>: '
    realMessage += name + "<" + email + ">\n"
    realMessage += 'Subject: ' + subject
    realMessage += '\nUser Agent:' + request.headers['User-Agent']
    realMessage += "\n\n" + message

    sendEmail('*****@*****.**', '*****@*****.**',
              'Isadore Contact Form', realMessage)

    return HTTPResponse(output="Email sent", status=204)
Esempio n. 22
0
    def sendAlarmNotice(self, short_name, alarm_id, alarm_type_id, event_time,
                        conn, msg):
        cur = conn.cursor()
        sql = """SELECT account.email FROM account, alarm WHERE account.id=alarm.account_id AND account.enabled_p and
            alarm.id = %s AND alarm.id IN (SELECT alarm_id FROM alarm_contact WHERE alarm_contact_type_id = %s)"""
        cur.execute(sql, (alarm_id, self.ALARM_CONTACT_TYPE_EMAIL))
        row = cur.fetchone()
        email = None
        if row:
            email = row[0]

        sql = """SELECT account.phone FROM account, alarm WHERE account.id=alarm.account_id AND account.enabled_p and
            alarm.id = %s AND alarm.id IN (SELECT alarm_id FROM alarm_contact WHERE alarm_contact_type_id = %s)"""
        cur.execute(sql, (alarm_id, self.ALARM_CONTACT_TYPE_SMS))
        row = cur.fetchone()
        sms = None
        if row:
            sms = row[0]

        if alarm_type_id == self.ALARM_TYPE_SENSOR_TEMP:
            amsg = short_name + ": At least one bin triggered alarm " + msg + " starting on " + \
                util.datetimeToReadableWithTZ(event_time, self.tz)
            if email:
                try:
                    logging.debug("sendEmail to " + email + ": " + amsg)
                    util.sendEmail(email, "*****@*****.**",
                                   "Isadore Alarm: Temperature Condition",
                                   amsg)
                except:
                    logging.error(traceback.format_exc())
            if sms:
                try:
                    # Send SMS
                    logging.debug("sendSMS to " + sms + ": " + amsg)
                    util.sendTxt(sms, amsg)
                except:
                    logging.error(traceback.format_exc())
Esempio n. 23
0
 def sendAlarmNotices(self):
     sql = "SELECT DISTINCT account.email FROM account, alarm WHERE account.id=alarm.account_id AND alarm.alarm_type_id = %s AND alarm.id IN (SELECT alarm_id from alarm_contact WHERE alarm_contact_type_id = %s)"
     cursor = self.conn.cursor()
     cursor.execute(
         sql, (self.ALARM_TYPE_MID_DOWN, self.ALARM_CONTACT_TYPE_EMAIL))
     emails = []
     for row in cursor:
         emails.append(row[0])
     sql = "SELECT DISTINCT account.phone FROM account, alarm WHERE account.id=alarm.account_id AND alarm.alarm_type_id = %s AND alarm.id IN (SELECT alarm_id from alarm_contact WHERE alarm_contact_type_id = %s)"
     cursor.execute(sql,
                    (self.ALARM_TYPE_MID_DOWN, self.ALARM_CONTACT_TYPE_SMS))
     sms = []
     for row in cursor:
         sms.append(row[0])
     if (emails):
         for email in emails:
             logging.debug("sendEmail to " + email + ": " +
                           (self.msg % util.datetimeToReadable(self.now)))
             util.sendEmail(email, "*****@*****.**",
                            self.subject, self.msg)
     if (sms):
         #alerts.send_SMS(sms, msg)
         logging.debug("sendSMS to " + str(sms) + ": " + self.shortMsg)
     cursor.close()
Esempio n. 24
0
    def post(self):
        global VerifyLinkIDLength
        email = self.get_argument('email', None)
        if not db.valid['email'].match(email):
            self.render("invite.html",
                        message="Please enter a valid email address.")
        else:
            with db.getCur() as cur:
                cur.execute("SELECT Email from Users where Email = ?",
                            (email, ))
                try:
                    existing = cur.fetchone()[0]
                    self.render(
                        "message.html",
                        message="Account for {0} already exists.".format(
                            email),
                        title="Duplicate Account")
                    return
                except:
                    pass
                code = util.randString(VerifyLinkIDLength)
                cur.execute(
                    "INSERT INTO VerifyLinks (Id, Email, Expires) "
                    "VALUES (?, LOWER(?), ?)",
                    (code, email, expiration_date().isoformat()))

            util.sendEmail(
                email, "Your {0} Account".format(settings.WEBSITENAME),
                format_invite(settings.WEBSITENAME, this_server(self.request),
                              code))

            self.render(
                "message.html",
                message="Invite sent. It will expire in {0} days.".format(
                    settings.LINKVALIDDAYS),
                title="Invite")
Esempio n. 25
0
        margin: 0 auto;
      }
    </style>
    <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
  </head>
  <body>
    <div class="body">
      <div class="header">
        <span>Error in phpipam</span>
      </div>
      <div class="content">
        <h2>The following error occured in copycat-master.py:</h2>
        <pre class="prettyprint">""" + s + """        </pre>
      </div>
      <div class="footer">
        <span>phpipam</span>
      </div>
    </div>
  </body>
</html>"""

if __name__ == '__main__':
    try:
        print "hello" + 3 + False
    except:
        error = 'Failure: ' + str(sys.exc_info()[0])
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        tracebk = ''.join('!! ' + line for line in lines)
        sendEmail(["*****@*****.**"], "[copycat] -- ERROR -- util.py", "*****@*****.**", getEmailBody(error + "\n" + tracebk))
Esempio n. 26
0
		# check to see if solar voltage is > 4.0 on pi



		if (solarvoltage > 4.0):
			print "solar voltage > 4.0"
		
			#if temp inside is too hot and outside is cooler, turn fan on

			if ((insidetemperature > conf.FAN_ON_TEMPERATURE) and (insidetemperature >= outsidetemperature)):
				hardwareactions.setfan(True)	
				pclogging.log(pclogging.INFO, __name__, "fanON insidetemp> FAN_ON_TEMPERATURE and inside > outside")
				# send an email that the fan turned on
				message = "Fan turning ON:  State: ot:%3.2f it:%3.2f oh:%3.2f ih:%3.2f sv:%3.2f" % (outsidetemperature, insidetemperature, outsidehumidity, insidehumidity, solarvoltage)
				util.sendEmail("test", message, "ProjectCuracao Fan ON(TMP)",  conf.notifyAddress,  conf.fromAddress, "");
				print "monitorSystems Turning FAN ON" 

			#if humidity inside is too high and outside is less, turn fan on

			if ((insidehumidity > conf.FAN_ON_HUMIDITY) and (insidehumidity >  outsidehumidity)):
				hardwareactions.setfan(True)	
				pclogging.log(pclogging.INFO, __name__, "fanON insidehumid> FAN_ON_HUMIDITY  and inside > outside")
				message = "Fan turning ON:  State: ot:%3.2f it:%3.2f oh:%3.2f ih:%3.2f sv:%3.2f" % (outsidetemperature, insidetemperature, outsidehumidity, insidehumidity, solarvoltage)
				util.sendEmail("test",message, "ProjectCuracao Fan ON(HUM)",  conf.notifyAddress,  conf.fromAddress, "");
				print "monitorSystems Turning FAN ON" 

		else:
			# no point if solar voltage on Pi power supply is below 4V

			print "solar voltage <= 4.0"
def arduino_callback(channel):
    global hasBWInterrupted
    print('Edge detected on channel %s'%channel)
    hasBWInterrupted = True
    print("hasBWSet-2=", hasBWInterrupted)


if __name__ == '__main__':


    # system setup
    
    # log system startup
 
    pclogging.log(pclogging.INFO, __name__, "Project Curacao Startup")
    util.sendEmail("test", "ProjectCuracao Pi Startup", "The Raspberry Pi has rebooted.", conf.notifyAddress,  conf.fromAddress, "");
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BOARD)	
    GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN)
    # set initial hardware actions 
    hardwareactions.setfan(False)

    # arudino interrupt - from battery watchdog
    hasBWInterrupted = False  # interrupt state variable
    #GPIO.setup(11, GPIO.IN )
    GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    #GPIO.add_event_detect(11, GPIO.RISING, callback=arduino_callback)  # add rising edge detection on a channel
    #GPIO.add_event_detect(11, GPIO.RISING)  # add rising edge detection on a channel


Esempio n. 28
0
 def run(self):
     subprocess.call('site/scripts/zip.sh ' + self.account + ' ' + self.loc,
                     shell=True)
     subject = '%s has been Zipped!' % self.loc
     body = self.loc + ' has been zipped.  You can download the zip file from within the %s directory' % self.loc
     sendEmail('*****@*****.**', self.emailTo, subject, body)
Esempio n. 29
0
#!/usr/bin/env python
import sys;
import os;
scriptsDir = os.environ.get("UTIL_SCRIPTS_DIR");
if (scriptsDir is None):
    raise Exception("Please set environment variable UTIL_SCRIPTS_DIR");
sys.path.insert(0,scriptsDir);
import pathSetter;
import util;

util.sendEmail("*****@*****.**", "*****@*****.**", "You've got male!", 
                "I realised my explanation was a little incomplete, so I wrote a script at /home/avanti/demo/emailExample.py that has the bare essentials.\n\n"
                +"If you just set the environment variable UTIL_SCRIPTS_DIR to point to /home/pgreens/av_scripts, it should work.\n\nP.S. now you can do email spoofing and scare people.");
Esempio n. 30
0
    hasBWInterrupted = True
    print("hasBWSet-2=", hasBWInterrupted)


if __name__ == '__main__':


    # system setup
    
    # log system startup
 
    pclogging.log(pclogging.INFO, __name__, "Project Curacao Startup")

    try:
    	myIP = util.track_ip()
    	util.sendEmail("test", "ProjectCuracao Pi Startup\n" + str(myIP), "The Raspberry Pi has rebooted.", conf.notifyAddress,  conf.fromAddress, "");
    	util.sendEmail("test", "ProjectCuracao Pi Startup\n" + str(myIP), "The Raspberry Pi has rebooted.", conf.secondaryNotifyAddress,  conf.fromAddress, "");

    except:
    	pclogging.log(pclogging.INFO, __name__, "Email / IP fetch failed (Internet down)")


    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BOARD)	
    GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN)
    # set initial hardware actions 
    hardwareactions.setfan(False)

    # arudino interrupt - from battery watchdog
    hasBWInterrupted = False  # interrupt state variable
    #GPIO.setup(11, GPIO.IN )
Esempio n. 31
0
	def run (self):
		subprocess.call('site/scripts/zip.sh ' + self.account + ' ' + self.loc, shell=True)
		subject = '%s has been Zipped!' % self.loc
		body = self.loc + ' has been zipped.  You can download the zip file from within the %s directory' % self.loc
		sendEmail('*****@*****.**', self.emailTo, subject, body)
Esempio n. 32
0
import time



sys.path.append('./datacollect')
sys.path.append('./graphprep')
sys.path.append('./hardware')
sys.path.append('./housekeeping')
sys.path.append('./actions')
sys.path.append('./util')

import util 
import hardwareactions

#if conflocal.py is not found, import default conf.py

# Check for user imports
try:
	import conflocal as conf
except ImportError:
	import conf

print("conf.notifyAddress", conf.notifyAddress)
print("conf.fromAddress", conf.fromAddress)

myIP = util.track_ip()


util.sendEmail("test", "hello from ProjectCuracao\n"+str(myIP), "Test from Pi", conf.notifyAddress, conf.fromAddress, "/home/pi/RasPiConnectServer/static/picamera.jpg");