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()
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
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!")
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)
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()
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
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 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)
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)
def all_transformers(): return [ Email(), SMS(), FBMsg(), Phone(), BankWire(), Paypal(), DebitCard(), ContactlessCard(), Tube(), FBStatus(), Tweet(), ]
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)
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)
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
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)
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()
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)
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
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
def __init__(self): self.sms = SMS() self.greenbutton = GreenButton() self.duration = 60 * 24 * 3600 self.start = int(time.time()) - 24 * 3600 - self.duration
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)
def get_sms(uri): export = os.environ['USERPROFILE'] + '\\Desktop\\sms' run_command(adb_commands['db'] + uri + ' > ' + export) sms = SMS(export) return sms
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
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")