Beispiel #1
0
    def add(self, msisdn, credit):
        sub = Subscriber()
        sms = SMS();
        try:
            mysub = sub.get(msisdn)
        except SubscriberException as e:
            raise CreditException(e)

        current_balance = sub.get_balance(msisdn)
        new_balance = Decimal(str(credit)) + Decimal(str(current_balance))

        # update subscriber balance
        try:
            cur = db_conn.cursor()
            cur.execute('UPDATE subscribers SET balance=%(new_balance)s WHERE msisdn=%(msisdn)s', {'new_balance': Decimal(str(new_balance)), 'msisdn': msisdn})
            sms.send(config['smsc'], msisdn, sms_credit_added % (credit, new_balance))
        except psycopg2.DatabaseError as e:
            raise CreditException('PG_HLR error updating subscriber balance: %s' % e)

        # insert transaction into the credit history
        try:
            cur = db_conn.cursor()
            cur.execute('INSERT INTO credit_history(msisdn,previous_balance,current_balance,amount) VALUES(%s,%s,%s,%s)', (msisdn, current_balance, new_balance, credit))
        except psycopg2.DatabaseError as e:
            db_conn.rollback()
            raise CreditException('PG_HLR error inserting invoice in the history: %s' % e)
        finally:
            db_conn.commit()
Beispiel #2
0
 def deactivate_subscriptions(self, msg):
     try:
         sms = SMS()
         sub = Subscriber()
         cur = db_conn.cursor()
         cur.execute(
             'SELECT msisdn FROM subscribers WHERE subscription_status = 0 AND authorized = 1'
         )
         count = cur.rowcount
         if count > 0:
             self.logger.info('Found %d subscribers to be deactivated' %
                              count)
             subscribers_list = cur.fetchall()
             db_conn.commit()
             for mysub in subscribers_list:
                 self.logger.debug(
                     'Send SMS that account is deactivated to %s' %
                     mysub[0])
                 sms.send(config['smsc'], mysub[0], msg)
                 # disable subscriber
                 try:
                     sub.authorized(mysub[0], 0)
                 except SubscriberException as e:
                     raise SubscriptionException(
                         'PG_HLR error in deactivating subscription: %s' %
                         e)
         else:
             db_conn.commit()
             self.logger.info('No subscribers need to be deactivate')
     except psycopg2.DatabaseError as e:
         raise SubscriptionException(
             'PG_HLR error in checking subscriptions to deactivate: %s' % e)
Beispiel #3
0
def send_smses(request):
    if request.method == "POST":
        if "message" in request.POST:
            numbers = set(c.phone_number for c in Contact.objects.all())
            SMS.send_sms(request.POST["message"], ["0780142469"])
            
            messages.info(request, "%d messages queued" % len(numbers))
    return redirect("home")
Beispiel #4
0
def main():
    if len(sys.argv) < 5:
        print("Not enough arguments", file=sys.stderr)
        # return 1

    HubToClass = open(sys.argv[1], 'wb')
    ClassToHub = open(sys.argv[2], 'rb')
    HubToInterface = open(sys.argv[3], 'wb')
    InterfaceToHub = open(sys.argv[4], 'rb')
    #ser = AutoSerial("/dev/ttyAMA0")
    ser = serial.Serial("/dev/ttyUSB0")

    std = SMS(sys.stdin, sys.stdout)
    classification = SMS(ClassToHub, HubToClass)
    interface = SMS(InterfaceToHub, HubToInterface)
    arduino = SMS(ser, ser, "serial")

    allPipes = [classification, interface, arduino]
    pipeMap = {
        SMS.Address.Broadcast: [classification, interface, arduino],
        SMS.Address.Individualization: [arduino],
        SMS.Address.Classification: [classification],
        SMS.Address.Distribuition: [arduino],
        SMS.Address.Interface: [interface],
    }

    print("Hub")

    while 1:
        for pipe in allPipes:
            if pipe.isData():
                address, mtype, data = pipe.readPacket()
                if address == 0:
                    name = "broad"
                elif address == 1:
                    name = "inv"
                elif address == 2:
                    name = "class"
                elif address == 3:
                    name = "dist"
                elif address == 4:
                    name = "inter"
                else:
                    name = error

                print(f'{name}: {address}, {mtype}, {data}')
                pipeArray = getRedirectStream(pipeMap, address)
                for redirPipe in pipeArray:
                    redirPipe.sendPacket(address, mtype, data)

        if std.isData():
            c = std.read()
            if c == '\x1b':  # x1b is ESC
                break

    ser.close()
class Analytics(object):
    def __init__(self):
        self.sms = SMS()
        self.greenbutton = GreenButton()
        self.duration = 60 * 24 * 3600
        self.start = int(time.time()) - 24 * 3600 - self.duration

    def run(self, user_id):
        user = db.User.get(db.User.id == user_id)
        xml = self.greenbutton.getUsagePointData(user.token, self.start, self.duration)

        soup = BeautifulSoup(xml)

        # Locate the data we care about
        blocks = []
        for entry in soup.find_all('entry'):
            if entry.content and entry.content.find('ns2:intervalblock'):
                blocks = entry.content.find_all('ns2:intervalblock')

        # Group the data by weekday and by hour
        raw = {}
        for block in blocks:
            readings = block.find_all('ns2:intervalreading')
            for reading in readings:
                dt = datetime.fromtimestamp(int(reading.find('ns2:timeperiod').find('ns2:start').get_text()))
                weekday = dt.weekday()
                if weekday not in raw:
                    raw[weekday] = {}
                if dt.hour not in raw[weekday]:
                    raw[weekday][dt.hour] = []
                raw[weekday][dt.hour].append(int(reading.find('ns2:cost').get_text()))

        # Determine the average for each hour on each weekday
        averages = {}
        for weekday in raw.keys():
            averages[weekday] = {}
            for hour in raw[weekday].keys():
                averages[weekday][hour] = sum(raw[weekday][hour]) / len(raw[weekday][hour])

        # Find the peak for whichever weekday tomorrow is
        tomorrow = datetime.today() + timedelta(days=1)
        weekday = (tomorrow.weekday() + 1) % 7
        today_averages = averages[weekday]
        peak_cost = 0
        peak_hour = 0
        for hour in today_averages.keys():
            if today_averages[hour] > peak_cost:
                peak_cost = today_averages[hour]
                peak_hour = hour

        # Send that peak to the user's phone
        message = 'Welcome to Spring Gauge! Your peak usage on %ss is at %s%s. Try turning off some lights at that time.'
        peak = datetime(tomorrow.year, tomorrow.month, tomorrow.day, peak_hour)
        self.sms.send(user.phone, message % (tomorrow.strftime('%A'), int(peak.strftime('%I')), peak.strftime('%p')))

        return {'status': 'success'}
 def emit(self, record):
     """
     # @Synopsis  override emit method, to deal with the logging record
     #
     # @Args record
     #
     # @Returns nothing
     """
     msg = self.format(record)
     SMS.sendMessage(EnvConfig.SMS_RECEIVERS, msg)
 def emit(self, record):
     """
     # @Synopsis  override emit method, to deal with the logging record
     #
     # @Args record
     #
     # @Returns nothing
     """
     msg = self.format(record)
     SMS.sendMessage(self.receivers, msg)
Beispiel #8
0
    def send_subscription_fee_reminder(self, msg):
        try:
            subscribers_list = self.get_unpaid_subscriptions()
        except SubscriptionException as e:
            raise SubscribtionException('ERROR in getting unpaid subscriptions')

        sms = SMS()
        
        for mysub in subscribers_list:
            self.logger.debug("Send sms to %s %s" % (mysub[0], msg))
            sms.send(config['smsc'],mysub[0], msg)
Beispiel #9
0
    def send_subscription_fee_reminder(self, msg):
        try:
            subscribers_list = self.get_unpaid_subscriptions()
        except SubscriptionException as e:
            raise SubscribtionException(
                'ERROR in getting unpaid subscriptions')

        sms = SMS()

        for mysub in subscribers_list:
            self.logger.debug("Send sms to %s %s" % (mysub[0], msg))
            sms.send(config['smsc'], mysub[0], msg)
Beispiel #10
0
    def send_subscription_fee_notice(self, msg):
        # get all subscribers
        try:
            sub = Subscriber()
            subscribers_list = sub.get_all()
        except SubscriberException as e:
            raise SubscriptionException('%s' % e)

        sms = SMS()

        for mysub in subscribers_list:
            self.logger.debug("Send sms to %s %s" % (mysub[1], msg))
            sms.send(config['smsc'],mysub[1], msg)
Beispiel #11
0
    def send_subscription_fee_notice(self, msg):
        # get all subscribers
        try:
            sub = Subscriber()
            subscribers_list = sub.get_all()
        except SubscriberException as e:
            raise SubscriptionException('%s' % e)

        sms = SMS()

        for mysub in subscribers_list:
            self.logger.debug("Send sms to %s %s" % (mysub[1], msg))
            sms.send(config['smsc'], mysub[1], msg)
Beispiel #12
0
def check_reservations(driver, months, days, times_checked):
    try:
        # Go to reservations and pull up whistler
        reservations_page = "https://www.epicpass.com/plan-your-trip/lift-access/reservations.aspx"
        driver.get(reservations_page)

        resort_selector_id = "PassHolderReservationComponent_Resort_Selection"
        whistler_selector_value = '80'
        check_availability_button_id = "passHolderReservationsSearchButton"

        WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, resort_selector_id)))
        select = Select(driver.find_element_by_id(resort_selector_id))
        select.select_by_value(whistler_selector_value)
        WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.ID, check_availability_button_id)))
        check_availability_button = driver.find_element_by_id(check_availability_button_id)
        driver.execute_script("arguments[0].click();", check_availability_button)

        # Get correct month
        # TODO

        # Check for days
        calendar_div_xpath = "//div[@class='passholder_reservations__calendar__days']"
        WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, calendar_div_xpath)))
        time.sleep(1)
        calendar_el = driver.find_element_by_xpath(calendar_div_xpath)
        day_els = calendar_el.find_elements_by_tag_name("button")

        for day_el in day_els:
            if not day_el.get_attribute('disabled'):
                if day_el.text in days:
                    print("Times Checked: %s" % times_checked)
                    print("%s %s is now available!" % (month, day_el.text))
                    print("Found result at %s" % datetime.now().time())
                    if book_day(day_el, driver):
                        sms = SMS(config.phone_number, config.phone_carrier,
                                config.email_address, config.email_password)
                        sms.send("%s %s was attempted to be booked at Whistler Blackcomb.\n" \
                                "Please look for a confirmation email shortly." % (
                                month, day_el.text), "Reservation Found")
                        sys.exit()
                    else:
                        print("Error booking day")

        print("Times Checked: %s" % times_checked, end='\r')
    except TimeoutException:
        traceback.print_exc()
        print("Will try again...")
    finally:
        time.sleep(config.refresh_frequency_seconds)
Beispiel #13
0
    def newTracking(self, data, isRestart):
        self.mailer = Mailer()
        self.sms = SMS()
        data.pid = os.getpid()
        if not isRestart:
            if not data.saveToDB():
                self.mailer.send('vpoezde.com', '<*****@*****.**>',
                            data.emails + ["*****@*****.**"],
                            "Ошибка базы данных",
                            "plain",
                            "Произошла ошибка записи в базу данных. Пожалуйста, повторите попытку.")
                return
            self.mailer.send('vpoezde.com', '<*****@*****.**>',
                        data.emails,
                        "Ваша заявка %d принята (%s - %s)" % (data.uid, data.route_from, data.route_to),
                        "plain",
                        "Ваша заявка принята и запущена в работу. Заявке присвоен номер %s. Используйте этот номер для отмены заявки." % data.uid)
        
            self.sms.send("vpoezde.com", "Заявка принята. Используйте номер %s для отмены заявки" % data.uid, data)
        else:
            data.updateDynamicData()
            
        #signal.signal(signal.SIGHUP, self.activate)
        signal.signal(signal.SIGINT, self.shutdown)

        self.run(data)
Beispiel #14
0
    def get_messages(self):
        """Return the list of all the messages in the SIM
        """
        logger.info("Get all the messages from the SIM")
        entries = yield retry_on_sim_busy(self.gsm_sim.RetrieveMessagebook,
                                          'all')

        ret = []
        for entry in entries:
            #logger.debug("Got message %s", entry)
            index = entry[0]
            status = str(entry[1])  # "read"|"sent"|"unread"|"unsent"
            peer = str(entry[2])
            text = unicode(entry[3])
            properties = entry[4]
            timestamp = properties.get('timestamp', None)
            # TODO: make the direction arg a boolean
            direction = 'out' if status in ['sent', 'unsent'] else 'in'

            message = SMS(peer,
                          text,
                          direction,
                          status=status,
                          timestamp=timestamp,
                          sim_index=index)
            self.indexes[index] = message
            ret.append(message)

        logger.info("got %d messages", len(ret))
        yield ret
Beispiel #15
0
def get_sms(id):
    modem.send_AT_command(f'AT+CMGR={id}')
    response = modem.get_response()
    if response.strip() == 'ERROR':
        return jsonify(message = "ERROR"), 503
    else:
        lines = response.split('\r\n')
        return jsonify(sms = SMS(lines[1], lines[2], id).serialize()), 200
Beispiel #16
0
def sign_up(update: Update, context: CallbackContext) -> None:
    person = update.message.from_user
    phone = unidecode.unidecode(update.message.text)

    print("Phone of {}: {}".format(person.first_name, phone))
    keyboard = [[
        InlineKeyboardButton("📥ارسال مجدد", callback_data='retry'),
        InlineKeyboardButton("↩️بازگشت", callback_data='account')
    ]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text("پس از دریافت پیامک کد تایید وارد نمایید: ",
                              reply_markup=reply_markup)
    sms_api = SMS()
    code = sms_api.send(update.message.text)
    context.user_data['v_code'] = code
    context.user_data['phone'] = phone
    return FIFTH
Beispiel #17
0
    def __init__(self):
        self.haze = Haze.HazeAPI()
        self.dengue = dengue_api.Dengue()
        self.SMS = SMS.SMSAPI()
        self.twitter = twitter.TwitterAPI()
        self.email = email.EmailSend()

        self.telegram_api = telegram_api.TelegramAPI()
        self.cd_shelter = CD_Shelter_API.CDShelter()
Beispiel #18
0
    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)
        self.title("SEPCAP")
        self.geometry("800x480")
        self.attributes("-zoomed", True)
        self.overrideredirect(1)
        container = tk.Frame(self, width=800, height=480)
        container.pack(side="top", fill="both", expand=True)

        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        self.sms = SMS(open(sys.argv[1], "rb"), open(sys.argv[2], "wb"))

        lg = Image.open(IMG_LOGO)
        lg = lg.resize((70, 70), Image.ANTIALIAS)
        logo = ImageTk.PhotoImage(lg, Image.ANTIALIAS)

        pageId = (iniPage, menuSep, menuCont, separacao1, separacao2,
                  contagem1, contagem2, contagem3, calib1, calib2, calib3,
                  emergencyStop)

        pageName = ("", "MENU INICIAL", "MENU INICIAL", "SEPARAÇÃO",
                    "SEPARAÇÃO", "CONTAGEM", "CONTAGEM", "CONTAGEM",
                    "CALIBRAÇÃO", "CALIBRAÇÃO", "CALIBRAÇÃO", "")

        for F, pName in zip(pageId, pageName):
            frame = F(container, self)
            frame.config(cursor='none')
            if ((F != iniPage) and (F != emergencyStop)):
                canvas = tk.Canvas(frame,
                                   width=300,
                                   height=80,
                                   bg="black",
                                   highlightthickness=3)
                canvas.place(x=-5, y=30)
                logoTop = tk.Label(frame, image=logo, bg='black')
                logoTop.image = logo
                logoTop.place(x=5, y=35)
                w = tk.Label(frame,
                             text=pName,
                             font=("Paytone One", 20),
                             fg='white',
                             bg='black').place(x=75, y=48)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        global X, Y
        X = 0
        Y = 0
        self.frames[calib2].imgSep.bind('<Button-1>', calculate_coordinates)
        self.showFrame(iniPage)
        self.update()
    def init(self, ser):

        s = SMS(PORT, BAUD, loglevel=logging.DEBUG)
        s.setup()
        if not s.turnOn(): exit(1)
        if not s.setEchoOff(): exit(1)
        print("SIM800 module initalized succesfully!")
Beispiel #20
0
 def deactivate_subscriptions(self, msg):
     try:
         sms = SMS()
         sub = Subscriber()
         cur = db_conn.cursor()
         cur.execute('SELECT msisdn FROM subscribers WHERE subscription_status = 0')
         count = cur.rowcount
         if count > 0:
             self.logger.info('Found %d subscribers to be deactivated' % count)
             subscribers_list = cur.fetchall()
             for mysub in subscribers_list:
                 self.logger.debug('Send SMS that account is deactivated to %s' % mysub[0])
                 sms.send(config['smsc'],mysub[0], msg)
                 # disable subscriber
                 try:
                     sub.authorized(mysub[0], 0)
                 except SubscriberException as e:
                     raise SubscriptionException('PG_HLR error in deactivating subscription: %s' % e)
         else:
             self.logger.info('No subscribers need to be deactivate')
     except psycopg2.DatabaseError as e:
         raise SubscriptionException('PG_HLR error in checking subscriptions to deactivate: %s' % e)
Beispiel #21
0
def all_transformers():
    return [
        Email(),
        SMS(),
        FBMsg(),
        Phone(),
        BankWire(),
        Paypal(),
        DebitCard(),
        ContactlessCard(),
        Tube(),
        FBStatus(),
        Tweet(),
    ]
Beispiel #22
0
    def compare_market_data(self, last, current):
        now = datetime.now().strftime("%I:%M:%S")
        if changed_id := self.contracts_different(last, current):
            if last:
                print(
                    f'\n{self.flag} Change in contracts found at {now} {self.flag}\n'
                )
                SMS(predict_it.sms_api_key).sendSMS(
                    predict_it.alert_sms_number,
                    f"PredictIt Contract change found for {current['shortName']}\n{current['url']}"
                )
            else:
                print(f'\nInitial contracts found at {now} {self.flag}\n')

            self.display_single_market(current, callout=changed_id)
Beispiel #23
0
    def flag_new_ids(self, last, current):
        now = datetime.now().strftime("%I:%M:%S")
        if last and last != current:
            new_markets = list(set(current).difference(last))
            plural = 's' if len(new_markets) > 1 else ''
            print(
                f'\n{self.flag} New market{plural} found at {now} {self.flag}\n'
            )
            for market_id in new_markets:
                market_data = self.get_single_market(market_id)
                SMS(predict_it.sms_api_key).sendSMS(
                    predict_it.alert_sms_number,
                    f"New PredictIt Market found: {market_data['shortName']}\n{market_data['url']}"
                )
                self.display_single_market(market_data)
        else:
            print(f'{now} No new markets found')

        return copy(current)
Beispiel #24
0
    def __init__(self, device_path="/dev/ttyS0", encoding="utf-8"):
        # Set up logging
        # Set file name to current date and time
        self.longitude_history = set()
        self.latitude_history = set()
        self.encoding = encoding

        try:
            self.serial = serial.Serial(device_path, 115200)
        except OSError as e:
            print(
                f"Is the device properly configured to Pi?\n{e.errno}\n{e.traceback}"
            )
            sys.exit(1)

        # Create logs directory if it does not already exist
        Path("../logs/").mkdir(exist_ok=True)
        self.file_name = f"../logs/{datetime.now().strftime('%d-%m-%Y %H:%M:%S')}.txt"

        # Create an SMS object to send text messages if humans are detected
        self.sms = SMS()
Beispiel #25
0
def taskWorker():
    _redis = Redis()
    _redis.set("sim800NetworkStatus", "Unknown")
    _redis.set("sim800Balance", "0")
    _redis.set("sim800RSSI", 0)

    logger = logging.getLogger(LOGGER)
    balanceRegExp = re.compile(r"£(\d){1,2}\.(\d){2}")

    try:
        sms = SMS(PORT, BAUD, logger=logger)
        sms.setup()
        if not sms.turnOn():
            logger.critical("Failed to turn on SMS!")
            return
        if not sms.setEchoOff():
            logger.critical("Failed to set SMS echo off!")
            return
        sms.setTime(datetime.now())

        netStat = "Unknown"
        while netStat != "Good":
            netStat = sms.getNetworkStatus()
            if netStat is not None:
                if netStat in (NetworkStatus.RegisteredHome,
                               NetworkStatus.RegisteredRoaming):
                    netStat = "Good"
                elif netStat in (NetworkStatus.Searching, ):
                    netStat = "Searching"
                else:
                    netStat = "Bad"
            else:
                netStat = "Unknown"
            _redis.set("sim800NetworkStatus", netStat)

        checkBalance = True
        statusCheckTime = 0.
        while True:
            if taskQueue.empty():
                if checkBalance:
                    checkBalance = False
                    balanceMsg = sms.sendUSSD(BALANCE_USSD)
                    logger.info("Balance message: {}".format(balanceMsg))
                    match = balanceRegExp.search(balanceMsg)
                    if match is not None:
                        balance = match.group(0)
                        logger.info("Balance amount: {}".format(balance))
                        _redis.set("sim800Balance", balance)

                if (time.time() - statusCheckTime) > FIVE_MINUTES:
                    rssi = sms.getRSSI()
                    if rssi is not None: rssi = (rssi.value / 4.) * 100
                    else: rssi = 0
                    _redis.set("sim800RSSI", rssi)

                    netStat = sms.getNetworkStatus()
                    if netStat is not None:
                        if netStat in (NetworkStatus.RegisteredHome,
                                       NetworkStatus.RegisteredRoaming):
                            netStat = "Good"
                        elif netStat in (NetworkStatus.Searching, ):
                            netStat = "Searching"
                        else:
                            netStat = "Bad"
                    else:
                        netStat = "Unknown"
                    _redis.set("sim800NetworkStatus", netStat)

                    statusCheckTime = time.time()

            try:
                task = taskQueue.get(timeout=60)
            except Empty:
                continue
            if task is None: continue

            phoneNumber = task.get('phoneNumber')
            message = task.get('message')

            if phoneNumber and message:
                logger.info("Sending SMS: {}, {}".format(phoneNumber, message))
                if sms.sendSMS(phoneNumber, message):
                    logger.info("SMS sent successfully")
                    checkBalance = True
                else:
                    logger.error("Failed to send SMS! {}, {}".format(
                        phoneNumber, message))
            else:
                logger.error("Task is not valid: {}".format(task))

            taskQueue.task_done()
    except Exception as e:
        logger.critical("Exception in task thread: {}".format(e))
        return
 def __init__(self):
     self.sms = SMS()
     self.greenbutton = GreenButton()
     self.duration = 60 * 24 * 3600
     self.start = int(time.time()) - 24 * 3600 - self.duration
Beispiel #27
0
from sms import SMS
import requests
try:
    r = requests.head("https://google.com")
    print(r.status_code)
except requests.ConnectionError:
    print("failed to connect")
    SMS("enter your number", "body of the msg")
Beispiel #28
0
if should_send_sms():
    if not 'SMS_SECRET' in os.environ:
        print("No SMS_SECRET for Twilio in environment variables")
        exit(0)
    if not 'SMS_AUTH' in os.environ:
        print("No SMS_SECRET for Twilio in environment variables")
        exit(0)
    if not 'PHONE_NUMBER' in os.environ:
        print("No PHONE_NUMBER for Twilio in environment variables")
        exit(0)
    if not 'SRC_PHONE_NUMBER' in os.environ:
        print("No SRC_PHONE_NUMBER for Twilio in environment variables")
        exit(0)

    sms = SMS(os.environ['SMS_SECRET'], os.environ['SMS_AUTH'])

sms_count = 0


def send_sms(msg):
    global sms_count
    global settings
    if should_send_sms() and sms_count < settings.max_sms_once:
        sms.send(os.environ['SRC_PHONE_NUMBER'], os.environ['PHONE_NUMBER'],
                 msg)
        sms_count += 1


prods = moreler.fetch_products(settings.search_tag, requester)
prods += xkomer.fetch_products(settings.search_tag, requester)
Beispiel #29
0
def parseXML(count):
    solr = searchManager()

    for message in root.findall('message'):
        id = message.get('id')
        text = message.find('text').text
        source = message.find('source')
        sender = source.find('srcNumber').text
        uprofile = source.find('userProfile')
        age = uprofile.find('age').text
        gender = uprofile.find('gender').text
        destination = message.find('destination')
        recipient = destination.find('destNumber').text
        mProfile = message.find('messageProfile')
        time = mProfile.get('time').strip()
        type = mProfile.get('type')

        newSms = SMS(
            id=id,
            text=text,
            sender=sender,
            recipient=recipient,
            age=age,
            gender=gender,
            time=time,
            type=type,
        )

        # print text, sender, recipient,  age, gender, time, type

        if sender in allSMS:
            if time == 'unknown':
                continue
            count += 1

            date = parseTime(time)
            if date == 'NA':
                print 'found faffdate: ', time
                continue
            currentUserSmsList = allSMS[sender]
            currentUserSmsList.append(newSms)
            allSMS[sender] = currentUserSmsList

            currentSmsDictList = allSMSDict[sender]
            currentSmsDictList.append(newSms.toDict())
            allSMSDict[sender] = currentSmsDictList
            #solr.addDocuments(id=id, sender=sender, recipient=recipient, text=text, date=date, polarity='NA')

            if recipient in allSMS:
                print 'recipeint has been a sender', recipient

        else:
            if time == 'unknown':
                continue
            count += 1

            date = parseTime(time)
            if date == 'NA':
                print 'found faffdate: ', time
                continue
            userSmsList = []
            userSmsList.append(newSms)
            allSMS[sender] = userSmsList

            currentSmsDictList = []
            currentSmsDictList.append(newSms.toDict())
            allSMSDict[sender] = currentSmsDictList
            #solr.addDocuments(id=id, sender=sender, recipient=recipient, text=text, date=date, polarity='NA')

    print 'processing complete, a total of: ', len(
        allSMS), ' unique people.', ' Total messages is: ', count
    # for sender, mesages in allSMS.items():
    #    print sender, ' sent a total of : ', len((mesages)), ' messages'

    for sender, mesages in allSMSDict.items():
        print sender, ' sent a total of : ', len((mesages)), ' messages'
        print(mesages)
Beispiel #30
0
        t.append(time_elapsed)
        vals.append(newval)

        # Rest for a bit.
        time.sleep(float(1 / piezo.sampling_freq))


# ------------------------------------------------------------------------
# Main script
# ------------------------------------------------------------------------
if __name__ == '__main__':

    print("Program Start")

    piezo = Piezo()
    sms = SMS()
    boiling = Event()

    # Initialize lists for time and sensor data.
    t = []
    vals = []

    # Using a fake data acquisition because of an ADC problem.
    daq = Thread(target=fake_daqloop, args=(t, vals))
    daq.start()
    print("Data acquisition started")

    #initial baseline measurement, first 10s of data
    time.sleep(10)
    print("Gathering base data")
    base_vals = vals
Beispiel #31
0
class Bot:
    """The main class"""

    def __init__(self, remote_addr = '', output_dir = '/var/log/bot'):
#        self.active = False
        self.terminated = False
        self.remote_addr = remote_addr
        self.output_dir = output_dir
        self.emergencyAddress = '*****@*****.**'
        
    def start(self, data_dict):

        data = trackingData.TrackingData()
        data.loadFromDict(data_dict)
        data.ip_addr = self.remote_addr
        data.script = os.path.dirname(os.path.abspath(__file__))
        # Проверяем на корректность номера поездов и даты
        checker = pageChecker.MZAErrorChecker()
        res = 255
        ret = {}
        for i in range(len(data.trains)):
            self.itemIndex = i
            while res == 255:
                try:
                    request = urllib2.Request(url="http://www.mza.ru/?exp=1", data=data.getPostAsString(i))
                    response = urllib2.urlopen(request)
                except urllib2.HTTPError as err:
                    ret["code"] = 1
                    ret["HTTPError"] = str(err.code)
                    return ret
                except urllib2.URLError as err:
                    ret["code"] = 1
                    ret["HTTPError"] = str(err.reason)
                    return ret
                res = checker.CheckPage(response.read())
                if res == 1: #express-3 request error
                    ret["code"] = 2
                    ret["TrainIndex"] = i
                    ret["ExpressError"] = checker.errorText
                    return ret
                elif res == 2: #station number is ambiguous
                    ret["code"] = 3
                    ret["StationNum"] = checker.stationNum
                    ret["StationOptions"] = checker.options
                    return ret
                elif res == 3: #station name is incorrect
                    ret["code"] = 4
                    ret["Station"] = checker.station
                    ret["StationError"] = checker.errorText
                    return ret

        #return on error
        if res != 0:
            ret["code"] = res
            return ret

        try:
            self.daemonize(target = self.newTracking, args = (data, False))
        except:
            self.emergencyMail("Daemonize exception", "Daemonize exception occured:\n %s\n" % (str(traceback.format_exc())))
            os._exit(1)

        ret["code"] = 0
        return ret


    def newTracking(self, data, isRestart):
        self.mailer = Mailer()
        self.sms = SMS()
        data.pid = os.getpid()
        if not isRestart:
            if not data.saveToDB():
                self.mailer.send('vpoezde.com', '<*****@*****.**>',
                            data.emails + ["*****@*****.**"],
                            "Ошибка базы данных",
                            "plain",
                            "Произошла ошибка записи в базу данных. Пожалуйста, повторите попытку.")
                return
            self.mailer.send('vpoezde.com', '<*****@*****.**>',
                        data.emails,
                        "Ваша заявка %d принята (%s - %s)" % (data.uid, data.route_from, data.route_to),
                        "plain",
                        "Ваша заявка принята и запущена в работу. Заявке присвоен номер %s. Используйте этот номер для отмены заявки." % data.uid)
        
            self.sms.send("vpoezde.com", "Заявка принята. Используйте номер %s для отмены заявки" % data.uid, data)
        else:
            data.updateDynamicData()
            
        #signal.signal(signal.SIGHUP, self.activate)
        signal.signal(signal.SIGINT, self.shutdown)

        self.run(data)
        
                    
    def activate(self, signum, frame):
        self.active = True
        
    def shutdown(self, signum, frame):
        self.terminated = True
             
    def run(self, data):
        prevs = [0 for i in range(len(data.trains))]
        while not self.terminated and data.expires > date.today():
            if datetime.now().hour == 3:
                time.sleep(60)
                continue
            for i in range(len(data.trains)):
                try:
                    request = urllib2.Request(url="http://www.mza.ru/?exp=1", data=data.getPostAsString(i))
                    response = urllib2.urlopen(request)
                except urllib2.HTTPError as err:
                    #self.HTTPError = err.code
                    time.sleep(60)
                    continue
                except urllib2.URLError as err:
                    #self.HTTPError = err.reason
                    time.sleep(60)
                    continue

                page = response.read()
                checker = pageChecker.MZAErrorChecker()
                if not checker.CheckPage(page) == 0:
                    time.sleep(60)
                    continue
                parser = MZAParser()
                if parser.ParsePage(page) != 0:
                    time.sleep(60)
                    continue

                filter = PlacesFilter()
                curr = filter.applyFilter(parser.result, data)
                if curr == 0 and curr < prevs[i]:
                    fd = open("%s/page.%d.html" % (self.output_dir, os.getpid()), "w")
                    fd.write(page)
                    fd.close()
                if curr > prevs[i]:
                    # new tickets have arrived!!!
                    #print "%d ==> %d" % (prevs[i], curr)
                    self.makeEmailText(data, i, filter.filteredPlaces)
                    self.mailer.send('vpoezde.com', '<*****@*****.**>',
                                data.emails,
                                "Билеты (+%d новых) [Заявка %d: %s - %s]" % (curr - prevs[i], data.uid, data.route_from, data.route_to),
                                "plain",
                                self.makeEmailText(data, i, filter.filteredPlaces))
                    self.sms.send("vpoezde.com", "%d билетов (%d новых): %s, поезд %s" % (curr, curr - prevs[i], data.trains[i][0].strftime("%d.%m.%Y"), data.trains[i][1]), data)
                prevs[i] = curr
            
            time.sleep(data.period)

        if self.terminated:
            self.mailer.send('vpoezde.com', '<*****@*****.**>', 
                        data.emails,
                        "Заявка %d (%s - %s) завершена" % (data.uid, data.route_from, data.route_to),
                        "plain",
                        "Заявка %d завершена. Спасибо за использование сервиса!" % (data.uid))

    def makeEmailText(self, data, train_index, places):
        text = data.trains[train_index][0].strftime("%d.%m.%Y")
        text += "\n%s - %s\n" % (data.route_from, data.route_to)
        text += "Поезд %s\n" % data.trains[train_index][1]
        text += "В продаже имеются следующие места:"
        # TODO: передавать тип вагона полностью
        for car in places:
            type = ""
            if car[1] == 1:
                type = "Сидячий"
            if car[1] == 2:
                type = "Плацкартный"
            elif car[1] == 3:
                type = "Купейный"
            elif car[1] == 4:
                type = "СВ"
            text += "\nВагон №%02d (%s): " % (car[0], type)
            for place in car[2]:
                text += str(place[0])
                if len(place) > 1:
                    if place[1] == 0:
                        text += "Ц"
                    elif place[1] == 1:
                        text += "М"
                    elif place[1] == 2:
                        text += "Ж"
                    elif place[1] == 3:
                        text += "С"
                if place != car[2][len(car[2]) - 1]:
                    text += ", "
        return text


    def stop(self, uid, email):
        data = trackingData.TrackingData()
        ret = {}
        ret["code"] = data.loadFromDB(uid)
        if not ret["code"] == 0:
            return ret
        if not email in data.emails:
            ret["code"] = 3
            return ret
        if data.pid == -1:
            ret["code"] = 4
            return ret
        try:
            os.kill(data.pid, signal.SIGINT)
        except:
            ret["code"] = 5
            return ret
        data.removeDynamicData()
        return ret


    def getTrainsList(self, route_from, route_to, departure_date):
        ret = {}
        try:
            data = trackingData.TrackingData()
            id = data.getStationId(route_from.encode('utf-8'))
            if not id == 0:
                sfrom = str(id)
            else:
                sfrom = route_from.encode('utf-8')
            id = data.getStationId(route_to.encode('utf-8'))
            if not id == 0:
                sto = str(id)
            else:
                sto = route_to.encode('utf-8')

            request = urllib2.Request(url="http://www.mza.ru/?exp=1", data="""ScheduleRoute_DepDate=%s
                                                             &ScheduleRoute_StationFrom=%s
                                                             &ScheduleRoute_StationTo=%s
                                                             &spr=ScheduleRoute
                                                             &submit=Показать
                                                             &ScheduleRoute_ArvTimeFrom=
                                                             &ScheduleRoute_ArvTimeTo=
                                                             &ScheduleRoute_DepTimeFrom=
                                                             &ScheduleRoute_DepTimeTo=""" % \
                                                             (date.fromtimestamp(departure_date).strftime("%d.%m.%Y"),
                                                             sfrom, sto))
            response = urllib2.urlopen(request)
        except urllib2.HTTPError as err:
            ret["code"] = 1
            ret["HTTPError"] = str(err.code)
            return ret
        except urllib2.URLError as err:
            ret["code"] = 1
            ret["HTTPError"] = str(err.reason)
            return ret
        checker = pageChecker.MZAErrorChecker()
        page = response.read()
        res = checker.CheckPage(page)
        if res == 1: #express-3 request error
            ret["code"] = 2
            ret["ExpressError"] = checker.errorText
            return ret
        elif res == 2: #station name is ambiguous
            ret["code"] = 3
            ret["StationNum"] = checker.stationNum
            ret["StationOptions"] = checker.options
            return ret
        elif res == 3: #station name is incorrect
            ret["code"] = 4
            ret["Station"] = checker.station
            ret["StationError"] = checker.errorText
            return ret
        parser = MZATrainsListParser()
        trains = parser.GetTrainsList(page)
        ret['code'] = 0
        ret['trains'] = trains
        return ret


    def call(self, request_text):
        try:
            rawreq = simplejson.loads(request_text)
            method = rawreq['method']
            params = rawreq.get('params', [])

            responseDict = {}
            responseDict['id'] = rawreq['id']
            responseDict['jsonrpc'] = rawreq['jsonrpc']

            try:
                response = getattr(self, method, None)(*params)
                responseDict['result'] = response
                responseDict['error'] = None
            except Exception as err:
                responseDict['error'] = err.args

            json_str = simplejson.dumps(responseDict)
        except:
            raise
        else:
            pass
        return json_str


    def daemonize(self, target, args):
        # detect libc location
        libc_path = '/lib/libc.so.6'
        if os.path.exists('/lib/i386-linux-gnu'):
            libc_path = '/lib/i386-linux-gnu/libc.so.6'
        # fork the first time (to make a non-session-leader child process)
        try:
            pid = os.fork()
        except OSError, e:
            raise RuntimeError("1st fork failed: %s [%d]" % (e.strerror, e.errno))
        if pid == 0:
            # detach from controlling terminal (to make child a session-leader)
            os.setsid()
            libc = dl.open(libc_path)
            libc.call('prctl', 15, 'bot', 0, 0, 0)
            try:
                pid = os.fork()
            except OSError, e:
                raise RuntimeError("2nd fork failed: %s [%d]" % (e.strerror, e.errno))
                raise Exception, "%s [%d]" % (e.strerror, e.errno)
            if pid == 0:
                os.chdir("/")
                os.umask(0)
            else:
                # child process is all done
                os._exit(0)
Beispiel #32
0
min_area = 30000    #change minimal area for capsule
blur = 9            #change value for blur
crop_p = 0.8       #proportion of crop 


# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 45
rawCapture = PiRGBArray(camera, size=(640, 480))
# allow the camera to warmup
time.sleep(0.1)


#comms initialization
sms = SMS(open(sys.argv[1], "rb"), open(sys.argv[2], "wb"))

#sends message to interface -
# "sep.jpg" was overwritten to show on calibration mode
def send_calib_message(image):
    cv.imwrite("sep.jpg", image)
    print("image was written")
    sms.sendPacket(
           SMS.Address.Interface, 
           SMS.Message.CalibrationConf.type, 
           0)
    

#while loop for video capturing
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
    # grab the raw NumPy array representing the image
Beispiel #33
0
class Analytics(object):
    def __init__(self):
        self.sms = SMS()
        self.greenbutton = GreenButton()
        self.duration = 60 * 24 * 3600
        self.start = int(time.time()) - 24 * 3600 - self.duration

    def run(self, user_id):
        user = db.User.get(db.User.id == user_id)
        xml = self.greenbutton.getUsagePointData(user.token, self.start,
                                                 self.duration)

        soup = BeautifulSoup(xml)

        # Locate the data we care about
        blocks = []
        for entry in soup.find_all('entry'):
            if entry.content and entry.content.find('ns2:intervalblock'):
                blocks = entry.content.find_all('ns2:intervalblock')

        # Group the data by weekday and by hour
        raw = {}
        for block in blocks:
            readings = block.find_all('ns2:intervalreading')
            for reading in readings:
                dt = datetime.fromtimestamp(
                    int(
                        reading.find('ns2:timeperiod').find(
                            'ns2:start').get_text()))
                weekday = dt.weekday()
                if weekday not in raw:
                    raw[weekday] = {}
                if dt.hour not in raw[weekday]:
                    raw[weekday][dt.hour] = []
                raw[weekday][dt.hour].append(
                    int(reading.find('ns2:cost').get_text()))

        # Determine the average for each hour on each weekday
        averages = {}
        for weekday in raw.keys():
            averages[weekday] = {}
            for hour in raw[weekday].keys():
                averages[weekday][hour] = sum(raw[weekday][hour]) / len(
                    raw[weekday][hour])

        # Find the peak for whichever weekday tomorrow is
        tomorrow = datetime.today() + timedelta(days=1)
        weekday = (tomorrow.weekday() + 1) % 7
        today_averages = averages[weekday]
        peak_cost = 0
        peak_hour = 0
        for hour in today_averages.keys():
            if today_averages[hour] > peak_cost:
                peak_cost = today_averages[hour]
                peak_hour = hour

        # Send that peak to the user's phone
        message = 'Welcome to Spring Gauge! Your peak usage on %ss is at %s%s. Try turning off some lights at that time.'
        peak = datetime(tomorrow.year, tomorrow.month, tomorrow.day, peak_hour)
        self.sms.send(
            user.phone,
            message % (tomorrow.strftime('%A'), int(
                peak.strftime('%I')), peak.strftime('%p')))

        return {'status': 'success'}
Beispiel #34
0
 def __init__(self):
     self.sms = SMS()
     self.greenbutton = GreenButton()
     self.duration = 60 * 24 * 3600
     self.start = int(time.time()) - 24 * 3600 - self.duration
Beispiel #35
0
def get_sms(uri):
    export = os.environ['USERPROFILE'] + '\\Desktop\\sms'
    run_command(adb_commands['db'] + uri + ' > ' + export)
    sms = SMS(export)
    return sms
Beispiel #36
0
def parseXML(count):
    solr = searchManager()

    for message in root.findall('message'):
        id = message.get('id')
        text = message.find('text').text
        source = message.find('source')
        sender = source.find('srcNumber').text
        uprofile = source.find('userProfile')
        age = uprofile.find('age').text
        gender = uprofile.find('gender').text
        destination = message.find('destination')
        recipient = destination.find('destNumber').text
        mProfile = message.find('messageProfile')
        time = mProfile.get('time').strip()
        type = mProfile.get('type')

        newSms = SMS(id=id, text=text, sender=sender, recipient=recipient, age=age, gender=gender, time=time,
                     type=type, )

        # print text, sender, recipient,  age, gender, time, type

        if sender in allSMS:
            if time == 'unknown':
                continue
            count += 1

            date = parseTime(time)
            if date == 'NA':
                print 'found faffdate: ', time
                continue
            currentUserSmsList = allSMS[sender]
            currentUserSmsList.append(newSms)
            allSMS[sender] = currentUserSmsList


            currentSmsDictList = allSMSDict[sender]
            currentSmsDictList.append(newSms.toDict())
            allSMSDict[sender] = currentSmsDictList
            #solr.addDocuments(id=id, sender=sender, recipient=recipient, text=text, date=date, polarity='NA')

            if recipient in allSMS:
                print 'recipeint has been a sender', recipient

        else:
            if time == 'unknown':
                continue
            count += 1

            date = parseTime(time)
            if date == 'NA':
                print 'found faffdate: ', time
                continue
            userSmsList = []
            userSmsList.append(newSms)
            allSMS[sender] = userSmsList

            currentSmsDictList = []
            currentSmsDictList.append(newSms.toDict())
            allSMSDict[sender] = currentSmsDictList
            #solr.addDocuments(id=id, sender=sender, recipient=recipient, text=text, date=date, polarity='NA')

    print 'processing complete, a total of: ', len(allSMS), ' unique people.', ' Total messages is: ', count
   # for sender, mesages in allSMS.items():
    #    print sender, ' sent a total of : ', len((mesages)), ' messages'

    for sender, mesages in allSMSDict.items():
        print sender, ' sent a total of : ', len((mesages)), ' messages'
        print(mesages)
Beispiel #37
0
def taskWorker():
    _redis=Redis()
    _redis.set("sim800NetworkStatus", "Unknown")
    _redis.set("sim800Balance","0")
    _redis.set("sim800RSSI",0)

    logger=logging.getLogger(LOGGER)
    balanceRegExp=re.compile(r"£(\d){1,2}\.(\d){2}")

    try:
        sms=SMS(PORT,BAUD,logger=logger)
        sms.setup()
        if not sms.turnOn():
            logger.critical("Failed to turn on SMS!")
            return
        if not sms.setEchoOff():
            logger.critical("Failed to set SMS echo off!")
            return
        sms.setTime(datetime.now())

        netStat="Unknown"
        while netStat!="Good":
            netStat=sms.getNetworkStatus()
            if netStat is not None:
                if netStat in (NetworkStatus.RegisteredHome, NetworkStatus.RegisteredRoaming):
                    netStat="Good"
                elif netStat in (NetworkStatus.Searching,): netStat="Searching"
                else: netStat="Bad"
            else: netStat="Unknown"
            _redis.set("sim800NetworkStatus", netStat)

        checkBalance=True
        statusCheckTime=0.
        while True:
            if taskQueue.empty():
                if checkBalance:
                    checkBalance=False
                    balanceMsg=sms.sendUSSD(BALANCE_USSD)
                    logger.info("Balance message: {}".format(balanceMsg))
                    match=balanceRegExp.search(balanceMsg)
                    if match is not None:
                        balance=match.group(0)
                        logger.info("Balance amount: {}".format(balance))
                        _redis.set("sim800Balance",balance)

                if (time.time()-statusCheckTime)>FIVE_MINUTES:
                    rssi=sms.getRSSI()
                    if rssi is not None: rssi=(rssi.value/4.)*100
                    else: rssi=0
                    _redis.set("sim800RSSI",rssi)
                    
                    netStat=sms.getNetworkStatus()
                    if netStat is not None:
                        if netStat in (NetworkStatus.RegisteredHome, NetworkStatus.RegisteredRoaming):
                            netStat="Good"
                        elif netStat in (NetworkStatus.Searching,): netStat="Searching"
                        else: netStat="Bad"
                    else: netStat="Unknown"
                    _redis.set("sim800NetworkStatus", netStat)

                    statusCheckTime=time.time()

            try: task=taskQueue.get(timeout=60)
            except Empty: continue
            if task is None: continue

            phoneNumber=task.get('phoneNumber')
            message=task.get('message')

            if phoneNumber and message:
                logger.info("Sending SMS: {}, {}".format(phoneNumber, message))
                if sms.sendSMS(phoneNumber, message):
                    logger.info("SMS sent successfully")
                    checkBalance=True
                else: logger.error("Failed to send SMS! {}, {}".format(phoneNumber, message))
            else: logger.error("Task is not valid: {}".format(task))

            taskQueue.task_done()
    except Exception as e:
        logger.critical("Exception in task thread: {}".format(e))
        return