Search is not available for this dataset
sample_type
stringclasses
3 values
node_type
stringclasses
6 values
file_path
stringlengths
13
93
prefix
stringlengths
0
4.1k
suffix
stringlengths
0
4.1k
middle
stringlengths
1
1.6k
text
stringlengths
131
8.36k
masked_node
if_statement
src/fw/util/mbuf_iterator.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mbuf_iterator.h" bool prv_iter_to_valid_mbuf(MBufIterator *iter) { // advance the iterator to the next MBuf with data while ((iter->m != NULL) && (mbuf_get_length(iter->m) == 0)) { iter->m = mbuf_get_next(iter->m); iter->data_index = 0; } return iter->m != NULL; } void mbuf_iterator_init(MBufIterator *iter, MBuf *m) { iter->m = m; iter->data_index = 0; prv_iter_to_valid_mbuf(iter); } bool mbuf_iterator_is_finished(MBufIterator *iter) { if (!prv_iter_to_valid_mbuf(iter)) { return true; } if (iter->data_index >= mbuf_get_length(iter->m)) { // we're at the end of this MBuf so move to the next one iter->m = mbuf_get_next(iter->m); iter->data_index = 0; // make sure this MBuf has data if (!prv_iter_to_valid_mbuf(iter)) { return true; } } return false; } bool mbuf_iterator_read_byte(MBufIterator *iter, uint8_t *data) {
uint8_t *buffer = mbuf_get_data(iter->m); *data = buffer[iter->data_index++]; return true; } bool mbuf_iterator_write_byte(MBufIterator *iter, uint8_t data) { if (mbuf_iterator_is_finished(iter)) { return false; } uint8_t *buffer = mbuf_get_data(iter->m); buffer[iter->data_index++] = data; return true; } MBuf *mbuf_iterator_get_current_mbuf(MBufIterator *iter) { return iter->m; }
if (mbuf_iterator_is_finished(iter)) { return false; }
<|repo_name|>pebble <|file_sep|>src/fw/util/mbuf_iterator.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mbuf_iterator.h" bool prv_iter_to_valid_mbuf(MBufIterator *iter) { // advance the iterator to the next MBuf with data while ((iter->m != NULL) && (mbuf_get_length(iter->m) == 0)) { iter->m = mbuf_get_next(iter->m); iter->data_index = 0; } return iter->m != NULL; } void mbuf_iterator_init(MBufIterator *iter, MBuf *m) { iter->m = m; iter->data_index = 0; prv_iter_to_valid_mbuf(iter); } bool mbuf_iterator_is_finished(MBufIterator *iter) { if (!prv_iter_to_valid_mbuf(iter)) { return true; } if (iter->data_index >= mbuf_get_length(iter->m)) { // we're at the end of this MBuf so move to the next one iter->m = mbuf_get_next(iter->m); iter->data_index = 0; // make sure this MBuf has data if (!prv_iter_to_valid_mbuf(iter)) { return true; } } return false; } bool mbuf_iterator_read_byte(MBufIterator *iter, uint8_t *data) { <|fim_suffix|> uint8_t *buffer = mbuf_get_data(iter->m); *data = buffer[iter->data_index++]; return true; } bool mbuf_iterator_write_byte(MBufIterator *iter, uint8_t data) { if (mbuf_iterator_is_finished(iter)) { return false; } uint8_t *buffer = mbuf_get_data(iter->m); buffer[iter->data_index++] = data; return true; } MBuf *mbuf_iterator_get_current_mbuf(MBufIterator *iter) { return iter->m; } <|fim_middle|>if (mbuf_iterator_is_finished(iter)) { return false; }<|endoftext|>
masked_node
compound_statement
src/fw/process_management/app_menu_data_source.c
kLaunch); const int override_cmp_rv = prv_app_override_comparator(app_node->install_id, new_node->install_id); if (is_app_quick_launch != is_new_quick_launch) { // Quick Launch only apps are first return (is_app_quick_launch ? 1 : 0) - (is_new_quick_launch ? 1 : 0); } else if (override_cmp_rv) { // Apps that override storage, record, and install order return (override_cmp_rv); } else if (app_node->storage_order != new_node->storage_order) { // Storage order (smallest first) return prv_comparator_ascending_zero_last(app_node->storage_order, new_node->storage_order); } else if (app_node->record_order != new_node->record_order) { // Record order (smallest first) return prv_comparator_ascending_zero_last(app_node->record_order, new_node->record_order); } else { // AppInstallId (smallest first) return new_node->install_id - app_node->install_id; } } static void prv_set_storage_order(AppMenuDataSource *source, AppMenuNode *menu_node, AppMenuOrderStorage *storage, bool update_and_take_ownership) { if (!storage) { return; } for (int i = 0; i < storage->list_length; i++) { const AppInstallId storage_app_id = storage->id_list[i]; if (storage_app_id == INSTALL_ID_INVALID) { continue; } const AppMenuStorageOrder new_storage_order = (AppMenuStorageOrder)i + AppMenuStorageOrderGeneralOrderOffset; if (menu_node && (menu_node->install_id == storage_app_id)) { menu_node->storage_order = new_storage_order; if (!update_and_take_ownership) { break; } else { continue; } } if (update_and_take_ownership) { AppMenuNode *other_node = prv_find_node_with_install_id(storage_app_id, source); if (other_node) { other_node->storage_order = new_storage_order; } } } if (update_and_take_ownership) { app_free(storage); } } static void prv_sorted_add(AppMenuDataSource *source, AppMenuNode *menu_node) { // Update the entire list order only if we've just read the order in this context. If we haven't // just read the order, then we're building a list starting from an empty list, so just set the // order for the new node. prv_set_storage_order(source, menu_node, source->order_storage ?: app_order_read_order(), (source->order_storage == NULL)); // If we're adding the Settings app node to the list and it hasn't received a storage order, // then give it its default order if ((menu_node->install_id == APP_ID_SETTINGS) && (menu_node->storage_order == AppMenuStorageOrder_NoOrder)) { menu_node->storage_order = AppMenuStorageOrder_SettingsDefaultOrder; } source->list = (AppMenuNode *)list_sorted_add(&source->list->node, &menu_node->node, prv_app_node_comparator, true /* ascending */); } //////////////////////////////// // AppInstallManager Callbacks //////////////////////////////// typedef struct InstallData { AppInstallId id; AppMenuDataSource *source; InstallEventType event_type; } InstallData; void prv_alert_data_source_changed(AppMenuDataSource *data_source) { if (data_source->callbacks.changed) { data_source->callbacks.changed(data_source->callback_context); } } static void prv_do_app_added(AppMenuDataSource *source, AppInstallId install_id); static void prv_do_app_removed(AppMenuDataSource *source, AppInstallId install_id); static void prv_do_app_icon_name_updated(AppMenuDataSource *source, AppInstallId install_id); static void prv_do_app_db_cleared(AppMenuDataSource *source); void prv_handle_app_event(void *data) { InstallData *install_data = data; AppMenuDataSource *source = install_data->source; AppInstallId install_id = install_data->id; switch (install_data->event_type)
kernel_free(install_data); } void prv_send_callback_to_app(AppMenuDataSource *data_source, AppInstallId install_id, InstallEventType event_type) { InstallData *install_data = kernel_malloc_check(sizeof(InstallData)); *install_data = (InstallData) { .id = install_id, .source = data_source, .event_type = event_type, }; process_manager_send_callback_event_to_process(PebbleTask_App, prv_handle_app_event, install_data); } //! Must be run from the app task static void prv_do_app_added(AppMenuDataSource *source, AppInstallId install_id) { AppInstallEntry entry; if (!app_install_get_entry_for_install_id(install_id, &entry) || prv_is_app_filtered_out(&entry, source)) { return; } add_app_with_install_id(&entry, source); prv_alert_data_source_changed(source); } //! Called when an application is installed static void prv_app_added_callback(const AppInstallId install_id, void *data) { AppMenuDataSource *data_source = data; prv_send_callback_to_app(data_source, install_id, APP_AVAILABLE); } //! Must be run from the app task static void prv_do_app_removed(AppMenuDataSource *source, AppInstallId install_id) { // Don't filter, just always try removing from the list: const bool is_removed = remove_app_with_install_id(install_id, source); if (is_removed) { prv_alert_data_source_changed(source); } } //! Called when an application is uninstalled static void prv_app_removed_callback(const AppInstallId install_id, void *data) { AppMenuDataSource *data_source = data; prv_send_callback_to_app(data_source, install_id, APP_REMOVED); } //! Must be run from the app task static void prv_do_app_icon_name_updated(AppMenuDataSource *source, AppInstallId install_id) { AppInstallEntry entry; if (!app_install_get_entry_for_install_id(install_id, &entry)) { return; } AppMenuNode *node = prv_find_node_with_install_id(install_id, source); if (prv_is_app_filtered_out(&entry, source)) { if (node == NULL) { // Changed and still excluded: return; } // Changed and is now excluded: prv_unload_node(source, node); } else { // Changed and is now included: if (node == NULL) { add_app_with_install_id(&entry, source); } } prv_alert_data_source_changed(source); } static void prv_app_icon_name_updated_callback(const AppInstallId install_id, void *data) { AppMenuDataSource *data_source = data; prv_send_callback_to_app(data_source, install_id, APP_ICON_NAME_UPDATED); } //! Must be run from the app task static void prv_do_app_db_cleared(AppMenuDataSource *source) { AppMenuNode *iter = source->list; while (iter) { AppMenuNode *temp = (AppMenuNode *)list_get_next((ListNode *)iter); // if the node belonged to the app_db, remove if (app_install_id_from_app_db(iter->install_id)) { prv_unload_node(source, iter); } iter = temp; } prv_alert_data_source_changed(source); } static void prv_app_db_cleared_callback(const AppInstallId install_id, void *data) { // data is just a pointer to the AppMenuDataSource prv_send_callback_to_app((AppMenuDataSource *)data, INSTALL_ID_INVALID, APP_DB_CLEARED); } static bool prv_app_enumerate_callback(AppInstallEntry *entry, void *data) { if (prv_is_app_filtered_out(entry, (AppMenuDataSource *)data)) { return true; // continue } add_app_with_install_id(entry, data); return true; // continue } //////////////////// // Add / remove helper functions: // This function should only be called once per app entry. The icon from the app will either be // loaded and cached or we will load the default system icon that is set by the client. static void prv_load_list_item_icon(AppMenuDataSource *source, AppMenuNode *node) { // Should only call this function if th
{ case APP_AVAILABLE: prv_do_app_added(source, install_id); break; case APP_REMOVED: prv_do_app_removed(source, install_id); break; case APP_ICON_NAME_UPDATED: prv_do_app_icon_name_updated(source, install_id); break; case APP_DB_CLEARED: prv_do_app_db_cleared(source); break; default: break; }
<|repo_name|>pebble <|file_sep|>src/fw/process_management/app_menu_data_source.c <|fim_prefix|>kLaunch); const int override_cmp_rv = prv_app_override_comparator(app_node->install_id, new_node->install_id); if (is_app_quick_launch != is_new_quick_launch) { // Quick Launch only apps are first return (is_app_quick_launch ? 1 : 0) - (is_new_quick_launch ? 1 : 0); } else if (override_cmp_rv) { // Apps that override storage, record, and install order return (override_cmp_rv); } else if (app_node->storage_order != new_node->storage_order) { // Storage order (smallest first) return prv_comparator_ascending_zero_last(app_node->storage_order, new_node->storage_order); } else if (app_node->record_order != new_node->record_order) { // Record order (smallest first) return prv_comparator_ascending_zero_last(app_node->record_order, new_node->record_order); } else { // AppInstallId (smallest first) return new_node->install_id - app_node->install_id; } } static void prv_set_storage_order(AppMenuDataSource *source, AppMenuNode *menu_node, AppMenuOrderStorage *storage, bool update_and_take_ownership) { if (!storage) { return; } for (int i = 0; i < storage->list_length; i++) { const AppInstallId storage_app_id = storage->id_list[i]; if (storage_app_id == INSTALL_ID_INVALID) { continue; } const AppMenuStorageOrder new_storage_order = (AppMenuStorageOrder)i + AppMenuStorageOrderGeneralOrderOffset; if (menu_node && (menu_node->install_id == storage_app_id)) { menu_node->storage_order = new_storage_order; if (!update_and_take_ownership) { break; } else { continue; } } if (update_and_take_ownership) { AppMenuNode *other_node = prv_find_node_with_install_id(storage_app_id, source); if (other_node) { other_node->storage_order = new_storage_order; } } } if (update_and_take_ownership) { app_free(storage); } } static void prv_sorted_add(AppMenuDataSource *source, AppMenuNode *menu_node) { // Update the entire list order only if we've just read the order in this context. If we haven't // just read the order, then we're building a list starting from an empty list, so just set the // order for the new node. prv_set_storage_order(source, menu_node, source->order_storage ?: app_order_read_order(), (source->order_storage == NULL)); // If we're adding the Settings app node to the list and it hasn't received a storage order, // then give it its default order if ((menu_node->install_id == APP_ID_SETTINGS) && (menu_node->storage_order == AppMenuStorageOrder_NoOrder)) { menu_node->storage_order = AppMenuStorageOrder_SettingsDefaultOrder; } source->list = (AppMenuNode *)list_sorted_add(&source->list->node, &menu_node->node, prv_app_node_comparator, true /* ascending */); } //////////////////////////////// // AppInstallManager Callbacks //////////////////////////////// typedef struct InstallData { AppInstallId id; AppMenuDataSource *source; InstallEventType event_type; } InstallData; void prv_alert_data_source_changed(AppMenuDataSource *data_source) { if (data_source->callbacks.changed) { data_source->callbacks.changed(data_source->callback_context); } } static void prv_do_app_added(AppMenuDataSource *source, AppInstallId install_id); static void prv_do_app_removed(AppMenuDataSource *source, AppInstallId install_id); static void prv_do_app_icon_name_updated(AppMenuDataSource *source, AppInstallId install_id); static void prv_do_app_db_cleared(AppMenuDataSource *source); void prv_handle_app_event(void *data) { InstallData *install_data = data; AppMenuDataSource *source = install_data->source; AppInstallId install_id = install_data->id; switch (install_data->event_type) <|fim_suffix|> kernel_free(install_data); } void prv_send_callback_to_app(AppMenuDataSource *data_source, AppInstallId install_id, InstallEventType event_type) { InstallData *install_data = kernel_malloc_check(sizeof(InstallData)); *install_data = (InstallData) { .id = install_id, .source = data_source, .event_type = event_type, }; process_manager_send_callback_event_to_process(PebbleTask_App, prv_handle_app_event, install_data); } //! Must be run from the app task static void prv_do_app_added(AppMenuDataSource *source, AppInstallId install_id) { AppInstallEntry entry; if (!app_install_get_entry_for_install_id(install_id, &entry) || prv_is_app_filtered_out(&entry, source)) { return; } add_app_with_install_id(&entry, source); prv_alert_data_source_changed(source); } //! Called when an application is installed static void prv_app_added_callback(const AppInstallId install_id, void *data) { AppMenuDataSource *data_source = data; prv_send_callback_to_app(data_source, install_id, APP_AVAILABLE); } //! Must be run from the app task static void prv_do_app_removed(AppMenuDataSource *source, AppInstallId install_id) { // Don't filter, just always try removing from the list: const bool is_removed = remove_app_with_install_id(install_id, source); if (is_removed) { prv_alert_data_source_changed(source); } } //! Called when an application is uninstalled static void prv_app_removed_callback(const AppInstallId install_id, void *data) { AppMenuDataSource *data_source = data; prv_send_callback_to_app(data_source, install_id, APP_REMOVED); } //! Must be run from the app task static void prv_do_app_icon_name_updated(AppMenuDataSource *source, AppInstallId install_id) { AppInstallEntry entry; if (!app_install_get_entry_for_install_id(install_id, &entry)) { return; } AppMenuNode *node = prv_find_node_with_install_id(install_id, source); if (prv_is_app_filtered_out(&entry, source)) { if (node == NULL) { // Changed and still excluded: return; } // Changed and is now excluded: prv_unload_node(source, node); } else { // Changed and is now included: if (node == NULL) { add_app_with_install_id(&entry, source); } } prv_alert_data_source_changed(source); } static void prv_app_icon_name_updated_callback(const AppInstallId install_id, void *data) { AppMenuDataSource *data_source = data; prv_send_callback_to_app(data_source, install_id, APP_ICON_NAME_UPDATED); } //! Must be run from the app task static void prv_do_app_db_cleared(AppMenuDataSource *source) { AppMenuNode *iter = source->list; while (iter) { AppMenuNode *temp = (AppMenuNode *)list_get_next((ListNode *)iter); // if the node belonged to the app_db, remove if (app_install_id_from_app_db(iter->install_id)) { prv_unload_node(source, iter); } iter = temp; } prv_alert_data_source_changed(source); } static void prv_app_db_cleared_callback(const AppInstallId install_id, void *data) { // data is just a pointer to the AppMenuDataSource prv_send_callback_to_app((AppMenuDataSource *)data, INSTALL_ID_INVALID, APP_DB_CLEARED); } static bool prv_app_enumerate_callback(AppInstallEntry *entry, void *data) { if (prv_is_app_filtered_out(entry, (AppMenuDataSource *)data)) { return true; // continue } add_app_with_install_id(entry, data); return true; // continue } //////////////////// // Add / remove helper functions: // This function should only be called once per app entry. The icon from the app will either be // loaded and cached or we will load the default system icon that is set by the client. static void prv_load_list_item_icon(AppMenuDataSource *source, AppMenuNode *node) { // Should only call this function if th<|fim_middle|>{ case APP_AVAILABLE: prv_do_app_added(source, install_id); break; case APP_REMOVED: prv_do_app_removed(source, install_id); break; case APP_ICON_NAME_UPDATED: prv_do_app_icon_name_updated(source, install_id); break; case APP_DB_CLEARED: prv_do_app_db_cleared(source); break; default: break; }<|endoftext|>
masked_node
argument_list
tests/fw/comm/test_gatt_client_subscriptions.c
scover_all(&s_device), BTErrnoOK); prv_simulate_and_assert_discovery_of_one_service(&s_device); fake_event_clear_last(); } void test_gatt_client_subscriptions__cleanup(void) { for (GAPLEClient c = 0; c < GAPLEClientNum; ++c) { gatt_client_subscriptions_cleanup_by_client(c); } gap_le_connection_deinit(); gatt_client_subscription_cleanup(); fake_pbl_malloc_check_net_allocs(); fake_pbl_malloc_clear_tracking(); } // ------------------------------------------------------------------------------------------------- // gatt_client_subscriptions_subscribe void test_gatt_client_subscriptions__subscribe_invalid_characteristic(void) { fake_kernel_malloc_mark(); BTErrno e = gatt_client_subscriptions_subscribe(BOGUS_CHARACTERISTIC, BLESubscriptionAny, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidParameter); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__subscribe_no_cccd(void) { // The random 128-bit Service UUID: Uuid service_uuid = UuidMake(0xF7, 0x68, 0x09, 0x5B, 0x1B, 0xFA, 0x4F, 0x63, 0x97, 0xEE, 0xFD, 0xED, 0xAC, 0x66, 0xF9, 0xB0); BLEService service; uint8_t num_copied = gatt_client_copy_service_refs_matching_uuid(&s_device, &service, 1, &service_uuid); cl_assert_equal_i(num_copied, 1); // UUID for Characteristic that has no CCCD: Uuid characteristic_uuid = UuidMake(0xF7, 0x68, 0x09, 0x5B, 0x1B, 0xFA, 0x4F, 0x63, 0x97, 0xEE, 0xFD, 0xED, 0xAC, 0x66, 0xF9, 0xB1); BLECharacteristic characteristic; num_copied = gatt_client_service_get_characteristics_matching_uuids(service, &characteristic, &characteristic_uuid, 1); cl_assert_equal_i(num_copied, 1); fake_kernel_malloc_mark(); // Try to subscribe to the non-subscribe-able characteristic: BTErrno e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionAny, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidParameter); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__subscribe_unsupported_subscription_type(void) { BTErrno e; BLECharacteristic characteristic = prv_get_indicatable_characteristic(); fake_kernel_malloc_mark(); // Try to subscribe for notifications to the indicatable (but not notify-able) characteristic: e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNotifications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidParameter); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); // Try to subscribe for indications to the indicatable characteristic: e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoOK); } void test_gatt_client_subscriptions__subscribe_already_subscribed(void) { BTErrno e; BLECharacteristic characteristic = prv_get_indicatable_characteristic(); e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoOK); fake_event_clear_last(); fake_kernel_malloc_mark(); // Subscribe again: e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidState); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__unsubscribe_pending_subscription(void) { BTErrno e; BLECharacteristic characteristic = prv_get_indicatable_characteristic(); e = gatt_client_subscriptions_subscribe
; cl_assert_equal_i(e, BTErrnoOK); fake_event_clear_last(); fake_kernel_malloc_mark(); // Un-subscribe, while subscribing process is still pending: e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNone, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidState); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__subscribe_oom_for_subscription_allocation(void) { fake_kernel_malloc_mark(); fake_malloc_set_largest_free_block(sizeof(GATTClientSubscriptionNode) - 1); BTErrno e = gatt_client_subscriptions_subscribe(prv_get_indicatable_characteristic(), BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoNotEnoughResources); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__subscribe_oom_for_buffer_allocation(void) { fake_kernel_malloc_mark(); fake_malloc_set_largest_free_block(sizeof(GATTClientSubscriptionNode)); BTErrno e = gatt_client_subscriptions_subscribe(prv_get_indicatable_characteristic(), BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoNotEnoughResources); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__subscribe_cccd_write_error(void) { s_write_descriptor_cccd_result = -1; fake_kernel_malloc_mark(); // Try to subscribe for indications to the indicatable characteristic: BTErrno e = gatt_client_subscriptions_subscribe(prv_get_indicatable_characteristic(), BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, -1); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__unsubscribe_no_clients_subscribed(void) { fake_kernel_malloc_mark(); BTErrno e; BLECharacteristic characteristic = prv_get_indicatable_characteristic(); e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNone, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidState); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__unsubscribe_not_subscribed_but_other_client_is(void) { BTErrno e; BLECharacteristic characteristic = prv_get_indicatable_characteristic(); e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientApp); cl_assert_equal_i(e, BTErrnoOK); fake_kernel_malloc_mark(); e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNone, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidState); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__subscribe_first_subscriber(void) { BLECharacteristic characteristic = prv_get_indicatable_characteristic(); BTErrno e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoOK); cl_assert_equal_i(s_last_cccd_value, BLESubscriptionIndications); prv_confirm_cccd_write(BLEGATTErrorSuccess); prv_assert_subscription_event(characteristic, BLESubscriptionIndications, BLEGATTErrorSuccess, true /* kernel */, false /* app */); } void test_gatt_client_subscriptions__subscribe_not_first_subscriber(void) { BLECharacteristic characteristic = prv_get_indicatable_characteristic(); // Subscribe kernel: BTErrno e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoOK); cl_assert_equal_i(s_last_cccd_value, BLESubscriptionIndications); // Simulate ge
(characteristic, BLESubscriptionIndications, GAPLEClientKernel)
<|repo_name|>pebble <|file_sep|>tests/fw/comm/test_gatt_client_subscriptions.c <|fim_prefix|>scover_all(&s_device), BTErrnoOK); prv_simulate_and_assert_discovery_of_one_service(&s_device); fake_event_clear_last(); } void test_gatt_client_subscriptions__cleanup(void) { for (GAPLEClient c = 0; c < GAPLEClientNum; ++c) { gatt_client_subscriptions_cleanup_by_client(c); } gap_le_connection_deinit(); gatt_client_subscription_cleanup(); fake_pbl_malloc_check_net_allocs(); fake_pbl_malloc_clear_tracking(); } // ------------------------------------------------------------------------------------------------- // gatt_client_subscriptions_subscribe void test_gatt_client_subscriptions__subscribe_invalid_characteristic(void) { fake_kernel_malloc_mark(); BTErrno e = gatt_client_subscriptions_subscribe(BOGUS_CHARACTERISTIC, BLESubscriptionAny, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidParameter); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__subscribe_no_cccd(void) { // The random 128-bit Service UUID: Uuid service_uuid = UuidMake(0xF7, 0x68, 0x09, 0x5B, 0x1B, 0xFA, 0x4F, 0x63, 0x97, 0xEE, 0xFD, 0xED, 0xAC, 0x66, 0xF9, 0xB0); BLEService service; uint8_t num_copied = gatt_client_copy_service_refs_matching_uuid(&s_device, &service, 1, &service_uuid); cl_assert_equal_i(num_copied, 1); // UUID for Characteristic that has no CCCD: Uuid characteristic_uuid = UuidMake(0xF7, 0x68, 0x09, 0x5B, 0x1B, 0xFA, 0x4F, 0x63, 0x97, 0xEE, 0xFD, 0xED, 0xAC, 0x66, 0xF9, 0xB1); BLECharacteristic characteristic; num_copied = gatt_client_service_get_characteristics_matching_uuids(service, &characteristic, &characteristic_uuid, 1); cl_assert_equal_i(num_copied, 1); fake_kernel_malloc_mark(); // Try to subscribe to the non-subscribe-able characteristic: BTErrno e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionAny, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidParameter); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__subscribe_unsupported_subscription_type(void) { BTErrno e; BLECharacteristic characteristic = prv_get_indicatable_characteristic(); fake_kernel_malloc_mark(); // Try to subscribe for notifications to the indicatable (but not notify-able) characteristic: e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNotifications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidParameter); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); // Try to subscribe for indications to the indicatable characteristic: e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoOK); } void test_gatt_client_subscriptions__subscribe_already_subscribed(void) { BTErrno e; BLECharacteristic characteristic = prv_get_indicatable_characteristic(); e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoOK); fake_event_clear_last(); fake_kernel_malloc_mark(); // Subscribe again: e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidState); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__unsubscribe_pending_subscription(void) { BTErrno e; BLECharacteristic characteristic = prv_get_indicatable_characteristic(); e = gatt_client_subscriptions_subscribe<|fim_suffix|>; cl_assert_equal_i(e, BTErrnoOK); fake_event_clear_last(); fake_kernel_malloc_mark(); // Un-subscribe, while subscribing process is still pending: e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNone, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidState); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__subscribe_oom_for_subscription_allocation(void) { fake_kernel_malloc_mark(); fake_malloc_set_largest_free_block(sizeof(GATTClientSubscriptionNode) - 1); BTErrno e = gatt_client_subscriptions_subscribe(prv_get_indicatable_characteristic(), BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoNotEnoughResources); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__subscribe_oom_for_buffer_allocation(void) { fake_kernel_malloc_mark(); fake_malloc_set_largest_free_block(sizeof(GATTClientSubscriptionNode)); BTErrno e = gatt_client_subscriptions_subscribe(prv_get_indicatable_characteristic(), BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoNotEnoughResources); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__subscribe_cccd_write_error(void) { s_write_descriptor_cccd_result = -1; fake_kernel_malloc_mark(); // Try to subscribe for indications to the indicatable characteristic: BTErrno e = gatt_client_subscriptions_subscribe(prv_get_indicatable_characteristic(), BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, -1); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__unsubscribe_no_clients_subscribed(void) { fake_kernel_malloc_mark(); BTErrno e; BLECharacteristic characteristic = prv_get_indicatable_characteristic(); e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNone, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidState); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__unsubscribe_not_subscribed_but_other_client_is(void) { BTErrno e; BLECharacteristic characteristic = prv_get_indicatable_characteristic(); e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientApp); cl_assert_equal_i(e, BTErrnoOK); fake_kernel_malloc_mark(); e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionNone, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoInvalidState); fake_kernel_malloc_mark_assert_equal(); prv_assert_no_event(); } void test_gatt_client_subscriptions__subscribe_first_subscriber(void) { BLECharacteristic characteristic = prv_get_indicatable_characteristic(); BTErrno e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoOK); cl_assert_equal_i(s_last_cccd_value, BLESubscriptionIndications); prv_confirm_cccd_write(BLEGATTErrorSuccess); prv_assert_subscription_event(characteristic, BLESubscriptionIndications, BLEGATTErrorSuccess, true /* kernel */, false /* app */); } void test_gatt_client_subscriptions__subscribe_not_first_subscriber(void) { BLECharacteristic characteristic = prv_get_indicatable_characteristic(); // Subscribe kernel: BTErrno e = gatt_client_subscriptions_subscribe(characteristic, BLESubscriptionIndications, GAPLEClientKernel); cl_assert_equal_i(e, BTErrnoOK); cl_assert_equal_i(s_last_cccd_value, BLESubscriptionIndications); // Simulate ge<|fim_middle|>(characteristic, BLESubscriptionIndications, GAPLEClientKernel)<|endoftext|>
masked_node
call_expression
src/fw/kernel/util/factory_reset.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "kernel/util/factory_reset.h" #include "drivers/rtc.h" #include "drivers/task_watchdog.h" #include "flash_region/filesystem_regions.h" #include "kernel/event_loop.h" #include "kernel/util/standby.h" #include "process_management/worker_manager.h" #include "services/common/event_service.h" #include "services/common/shared_prf_storage/shared_prf_storage.h" #include "services/common/system_task.h" #include "services/runlevel.h" #include "shell/normal/app_idle_timeout.h" #include "system/bootbits.h" #include "system/logging.h" #include "system/reboot_reason.h" #include "system/reset.h" #include "kernel/util/sleep.h" #if !RECOVERY_FW #include "services/normal/blob_db/pin_db.h" #include "services/normal/blob_db/reminder_db.h" #include "services/normal/filesystem/pfs.h" #include "services/normal/timeline/event.h" #endif static bool s_in_factory_reset = false; static void prv_factory_reset_non_pfs_data() { PBL_LOG_SYNC(LOG_LEVEL_INFO, "Factory resetting..."); // This function can block the system task for a long time. // Prevent callbacks being added to the system task so it doesn't overflow. system_task_block_callbacks(true /* block callbacks */); launcher_block_popups(true); worker_manager_disable(); event_service_clear_process_subscriptions(PebbleTask_App); shared_prf_storage_wipe_all(); services_set_runlevel(RunLevel_BareMinimum); app_idle_timeout_stop(); while (worker_manager_get_current_worker_md()) { // busy loop until the worker is killed psleep(3); } rtc_timezone_clear(); } void factory_reset_set_reason_and_reset(void) { RebootReason reason = { RebootReasonCode_FactoryResetReset, 0 }; reboot_reason_set(&reason); system_reset(); } static void prv_factory_reset_post(bool should_shutdown) { if (should_shutdown) { enter_standby(RebootReasonCode_FactoryResetShutdown); } else { factory_reset_set_reason_and_reset(); } } void factory_reset(bool should_shutdown) { s_in_factory_reset = true; prv_factory_reset_non_pfs_data(); // TODO: wipe the registry on tintin? filesystem_regions_erase_all(); #if !defined(RECOVERY_FW) // "First use" is part of the PRF image for Snowy boot_bit_set(BOOT_BIT_FORCE_PRF); #endif prv_factory_reset_post(should_shutdown); } #if !RECOVERY_FW void close_db_files() { // Deinit the databases and any clients timeline_event_deinit(); reminder_db_deinit(); pin_db_deinit(); } void factory_reset_fast(void *unused) { s_in_factory_reset = true; // disable the watchdog... we've got lots to do before we reset task_watchdog_mask_clear(pebble_task_get_current());
; prv_factory_reset_non_pfs_data(); pfs_remove_files(NULL); prv_factory_reset_post(false /* should_shutdown */); } #endif // !RECOVERY_FW //! Used by the mfg flow to kick us out the MFG firmware and into the conumer PRF that's stored //! on the external flash. void command_enter_consumer_mode(void) { boot_bit_set(BOOT_BIT_FORCE_PRF); factory_reset(true /* should_shutdown */); } bool factory_reset_ongoing(void) { return s_in_factory_reset; }
close_db_files()
<|repo_name|>pebble <|file_sep|>src/fw/kernel/util/factory_reset.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "kernel/util/factory_reset.h" #include "drivers/rtc.h" #include "drivers/task_watchdog.h" #include "flash_region/filesystem_regions.h" #include "kernel/event_loop.h" #include "kernel/util/standby.h" #include "process_management/worker_manager.h" #include "services/common/event_service.h" #include "services/common/shared_prf_storage/shared_prf_storage.h" #include "services/common/system_task.h" #include "services/runlevel.h" #include "shell/normal/app_idle_timeout.h" #include "system/bootbits.h" #include "system/logging.h" #include "system/reboot_reason.h" #include "system/reset.h" #include "kernel/util/sleep.h" #if !RECOVERY_FW #include "services/normal/blob_db/pin_db.h" #include "services/normal/blob_db/reminder_db.h" #include "services/normal/filesystem/pfs.h" #include "services/normal/timeline/event.h" #endif static bool s_in_factory_reset = false; static void prv_factory_reset_non_pfs_data() { PBL_LOG_SYNC(LOG_LEVEL_INFO, "Factory resetting..."); // This function can block the system task for a long time. // Prevent callbacks being added to the system task so it doesn't overflow. system_task_block_callbacks(true /* block callbacks */); launcher_block_popups(true); worker_manager_disable(); event_service_clear_process_subscriptions(PebbleTask_App); shared_prf_storage_wipe_all(); services_set_runlevel(RunLevel_BareMinimum); app_idle_timeout_stop(); while (worker_manager_get_current_worker_md()) { // busy loop until the worker is killed psleep(3); } rtc_timezone_clear(); } void factory_reset_set_reason_and_reset(void) { RebootReason reason = { RebootReasonCode_FactoryResetReset, 0 }; reboot_reason_set(&reason); system_reset(); } static void prv_factory_reset_post(bool should_shutdown) { if (should_shutdown) { enter_standby(RebootReasonCode_FactoryResetShutdown); } else { factory_reset_set_reason_and_reset(); } } void factory_reset(bool should_shutdown) { s_in_factory_reset = true; prv_factory_reset_non_pfs_data(); // TODO: wipe the registry on tintin? filesystem_regions_erase_all(); #if !defined(RECOVERY_FW) // "First use" is part of the PRF image for Snowy boot_bit_set(BOOT_BIT_FORCE_PRF); #endif prv_factory_reset_post(should_shutdown); } #if !RECOVERY_FW void close_db_files() { // Deinit the databases and any clients timeline_event_deinit(); reminder_db_deinit(); pin_db_deinit(); } void factory_reset_fast(void *unused) { s_in_factory_reset = true; // disable the watchdog... we've got lots to do before we reset task_watchdog_mask_clear(pebble_task_get_current()); <|fim_suffix|>; prv_factory_reset_non_pfs_data(); pfs_remove_files(NULL); prv_factory_reset_post(false /* should_shutdown */); } #endif // !RECOVERY_FW //! Used by the mfg flow to kick us out the MFG firmware and into the conumer PRF that's stored //! on the external flash. void command_enter_consumer_mode(void) { boot_bit_set(BOOT_BIT_FORCE_PRF); factory_reset(true /* should_shutdown */); } bool factory_reset_ongoing(void) { return s_in_factory_reset; } <|fim_middle|>close_db_files()<|endoftext|>
masked_node
call_expression
src/fw/services/normal/activity/health_util.c
0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "health_util.h" #include "services/common/i18n/i18n.h" #include "services/normal/activity/activity.h" #include "shell/prefs.h" #include "util/time/time.h" #include "util/units.h" #include "util/string.h" #include <limits.h> #include <stdio.h> #include <string.h> static void prv_convert_duration_to_hours_and_minutes(int duration_s, int *hours, int *minutes) { *hours = (duration_s / SECONDS_PER_HOUR) ?: INT_MIN; *minutes = ((duration_s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE) ?: INT_MIN; if (*minutes == INT_MIN && *hours == INT_MIN) { *hours = 0; } } int health_util_format_hours_and_minutes(char *buffer, size_t buffer_size, int duration_s, void *i18n_owner) { int hours; int minutes; prv_convert_duration_to_hours_and_minutes(duration_s, &hours, &minutes); int pos = 0; if (hours != INT_MIN) { pos += snprintf(buffer + pos, buffer_size - pos, i18n_get("%dH", i18n_owner), hours); if (minutes != INT_MIN && pos < (int)buffer_size - 1) { buffer[pos++] = ' '; } } if (minutes != INT_MIN) { pos += snprintf(buffer + pos, buffer_size - pos, i18n_get("%dM", i18n_owner), minutes); } return pos; } int health_util_format_hours_minutes_seconds(char *buffer, size_t buffer_size, int duration_s, bool leading_zero, void *i18n_owner) { const int hours = duration_s / SECONDS_PER_HOUR; const int minutes = (duration_s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE; const int seconds = (duration_s % SECONDS_PER_HOUR) % SECONDS_PER_MINUTE; if (hours > 0) { const char *fmt = leading_zero ? "%02d:%02d:%02d" : "%d:%02d:%02d"; return snprintf(buffer, buffer_size, i18n_get(fmt, i18n_owner), hours, minutes, seconds); } else { const char *fmt = leading_zero ? "%02d:%02d" : "%d:%02d"; return snprintf(buffer, buffer_size, i18n_get(fmt, i18n_owner), minutes, seconds); } } int health_util_format_minutes_and_seconds(char *buffer, size_t buffer_size, int duration_s, void *i18n_owner) { int minutes = duration_s / SECONDS_PER_MINUTE; int seconds = duration_s % SECONDS_PER_MINUTE; return snprintf(buffer, buffer_size, i18n_get("%d:%d", i18n_owner), minutes, seconds); } GTextNodeText *health_util_create_text_node(int buffer_size, GFont font, GColor color, GTextNodeContainer *container) { GTextNodeText *text_node = graphics_text_node_create_text(buffer_size); if (container) { graphics_text_node_container_add_child(container, &text_node->node); } text_node->font = font; text_node->color = color; return text_node; } GTextNodeText *health_util_create_text_node_with_text(const char *text, GFont font, GColor color, GTextNodeContainer *container) { GTextNodeText *text_node = health_util_create_text_node(0, font, color, container); text_node->text = text; return text_node; } void health_util_duration_to_hours_and_minutes_text_node(int duration_s, void *i18n_owner, GFont number_font, GFont units_font, GColor color, GTextNodeContainer *container) { int hours; int minutes; prv_convert_duration_to_hours_and_minutes(duration_s, &hours, &minutes); const int units_offset_y = fonts_get_font_height(number_font) - fonts_get_font_height(units_font); const int hours_and_minutes_buffer_size = sizeof("00"); if (hours != INT_MIN) { GTextNodeText *hours_text_node =
; snprintf((char *) hours_text_node->text, hours_and_minutes_buffer_size, i18n_get("%d", i18n_owner), hours); GTextNodeText *hours_units_text_node = health_util_create_text_node_with_text( i18n_get("H", i18n_owner), units_font, color, container); hours_units_text_node->node.offset.y = units_offset_y; } if (hours != INT_MIN && minutes != INT_MIN) { // add a space between the H and the number of minutes health_util_create_text_node_with_text(i18n_get(" ", i18n_owner), units_font, color, container); } if (minutes != INT_MIN) { GTextNodeText *minutes_text_node = health_util_create_text_node(hours_and_minutes_buffer_size, number_font, color, container); snprintf((char *) minutes_text_node->text, hours_and_minutes_buffer_size, i18n_get("%d", i18n_owner), minutes); GTextNodeText *minutes_units_text_node = health_util_create_text_node_with_text( i18n_get("M", i18n_owner), units_font, color, container); minutes_units_text_node->node.offset.y = units_offset_y; } } void health_util_convert_fraction_to_whole_and_decimal_part(int numerator, int denominator, int* whole_part, int *decimal_part) { const int figure = ROUND(numerator * 100, denominator * 10); *whole_part = figure / 10; *decimal_part = figure % 10; } int health_util_format_whole_and_decimal(char *buffer, size_t buffer_size, int numerator, int denominator) { int converted_distance_whole_part = 0; int converted_distance_decimal_part = 0; health_util_convert_fraction_to_whole_and_decimal_part(numerator, denominator, &converted_distance_whole_part, &converted_distance_decimal_part); const char *fmt_i18n = i18n_noop("%d.%d"); const int rv = snprintf(buffer, buffer_size, i18n_get(fmt_i18n, buffer), converted_distance_whole_part, converted_distance_decimal_part); i18n_free(fmt_i18n, buffer); return rv; } int health_util_get_distance_factor(void) { switch (shell_prefs_get_units_distance()) { case UnitsDistance_Miles: return METERS_PER_MILE; case UnitsDistance_KM: return METERS_PER_KM; case UnitsDistanceCount: break; } return 1; } const char *health_util_get_distance_string(const char *miles_string, const char *km_string) { switch (shell_prefs_get_units_distance()) { case UnitsDistance_Miles: return miles_string; case UnitsDistance_KM: return km_string; case UnitsDistanceCount: break; } return ""; } int health_util_format_distance(char *buffer, size_t buffer_size, uint32_t distance_m) { return health_util_format_whole_and_decimal(buffer, buffer_size, distance_m, health_util_get_distance_factor()); } void health_util_convert_distance_to_whole_and_decimal_part(int distance_m, int *whole_part, int *decimal_part) { const int conversion_factor = health_util_get_distance_factor(); health_util_convert_fraction_to_whole_and_decimal_part(distance_m, conversion_factor, whole_part, decimal_part); } time_t health_util_get_pace(int time_s, int distance_meter) { if (!distance_meter) { return 0; } return ROUND(time_s * health_util_get_distance_factor(), distance_meter); }
health_util_create_text_node(hours_and_minutes_buffer_size, number_font, color, container)
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/activity/health_util.c <|fim_prefix|>0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "health_util.h" #include "services/common/i18n/i18n.h" #include "services/normal/activity/activity.h" #include "shell/prefs.h" #include "util/time/time.h" #include "util/units.h" #include "util/string.h" #include <limits.h> #include <stdio.h> #include <string.h> static void prv_convert_duration_to_hours_and_minutes(int duration_s, int *hours, int *minutes) { *hours = (duration_s / SECONDS_PER_HOUR) ?: INT_MIN; *minutes = ((duration_s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE) ?: INT_MIN; if (*minutes == INT_MIN && *hours == INT_MIN) { *hours = 0; } } int health_util_format_hours_and_minutes(char *buffer, size_t buffer_size, int duration_s, void *i18n_owner) { int hours; int minutes; prv_convert_duration_to_hours_and_minutes(duration_s, &hours, &minutes); int pos = 0; if (hours != INT_MIN) { pos += snprintf(buffer + pos, buffer_size - pos, i18n_get("%dH", i18n_owner), hours); if (minutes != INT_MIN && pos < (int)buffer_size - 1) { buffer[pos++] = ' '; } } if (minutes != INT_MIN) { pos += snprintf(buffer + pos, buffer_size - pos, i18n_get("%dM", i18n_owner), minutes); } return pos; } int health_util_format_hours_minutes_seconds(char *buffer, size_t buffer_size, int duration_s, bool leading_zero, void *i18n_owner) { const int hours = duration_s / SECONDS_PER_HOUR; const int minutes = (duration_s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE; const int seconds = (duration_s % SECONDS_PER_HOUR) % SECONDS_PER_MINUTE; if (hours > 0) { const char *fmt = leading_zero ? "%02d:%02d:%02d" : "%d:%02d:%02d"; return snprintf(buffer, buffer_size, i18n_get(fmt, i18n_owner), hours, minutes, seconds); } else { const char *fmt = leading_zero ? "%02d:%02d" : "%d:%02d"; return snprintf(buffer, buffer_size, i18n_get(fmt, i18n_owner), minutes, seconds); } } int health_util_format_minutes_and_seconds(char *buffer, size_t buffer_size, int duration_s, void *i18n_owner) { int minutes = duration_s / SECONDS_PER_MINUTE; int seconds = duration_s % SECONDS_PER_MINUTE; return snprintf(buffer, buffer_size, i18n_get("%d:%d", i18n_owner), minutes, seconds); } GTextNodeText *health_util_create_text_node(int buffer_size, GFont font, GColor color, GTextNodeContainer *container) { GTextNodeText *text_node = graphics_text_node_create_text(buffer_size); if (container) { graphics_text_node_container_add_child(container, &text_node->node); } text_node->font = font; text_node->color = color; return text_node; } GTextNodeText *health_util_create_text_node_with_text(const char *text, GFont font, GColor color, GTextNodeContainer *container) { GTextNodeText *text_node = health_util_create_text_node(0, font, color, container); text_node->text = text; return text_node; } void health_util_duration_to_hours_and_minutes_text_node(int duration_s, void *i18n_owner, GFont number_font, GFont units_font, GColor color, GTextNodeContainer *container) { int hours; int minutes; prv_convert_duration_to_hours_and_minutes(duration_s, &hours, &minutes); const int units_offset_y = fonts_get_font_height(number_font) - fonts_get_font_height(units_font); const int hours_and_minutes_buffer_size = sizeof("00"); if (hours != INT_MIN) { GTextNodeText *hours_text_node = <|fim_suffix|>; snprintf((char *) hours_text_node->text, hours_and_minutes_buffer_size, i18n_get("%d", i18n_owner), hours); GTextNodeText *hours_units_text_node = health_util_create_text_node_with_text( i18n_get("H", i18n_owner), units_font, color, container); hours_units_text_node->node.offset.y = units_offset_y; } if (hours != INT_MIN && minutes != INT_MIN) { // add a space between the H and the number of minutes health_util_create_text_node_with_text(i18n_get(" ", i18n_owner), units_font, color, container); } if (minutes != INT_MIN) { GTextNodeText *minutes_text_node = health_util_create_text_node(hours_and_minutes_buffer_size, number_font, color, container); snprintf((char *) minutes_text_node->text, hours_and_minutes_buffer_size, i18n_get("%d", i18n_owner), minutes); GTextNodeText *minutes_units_text_node = health_util_create_text_node_with_text( i18n_get("M", i18n_owner), units_font, color, container); minutes_units_text_node->node.offset.y = units_offset_y; } } void health_util_convert_fraction_to_whole_and_decimal_part(int numerator, int denominator, int* whole_part, int *decimal_part) { const int figure = ROUND(numerator * 100, denominator * 10); *whole_part = figure / 10; *decimal_part = figure % 10; } int health_util_format_whole_and_decimal(char *buffer, size_t buffer_size, int numerator, int denominator) { int converted_distance_whole_part = 0; int converted_distance_decimal_part = 0; health_util_convert_fraction_to_whole_and_decimal_part(numerator, denominator, &converted_distance_whole_part, &converted_distance_decimal_part); const char *fmt_i18n = i18n_noop("%d.%d"); const int rv = snprintf(buffer, buffer_size, i18n_get(fmt_i18n, buffer), converted_distance_whole_part, converted_distance_decimal_part); i18n_free(fmt_i18n, buffer); return rv; } int health_util_get_distance_factor(void) { switch (shell_prefs_get_units_distance()) { case UnitsDistance_Miles: return METERS_PER_MILE; case UnitsDistance_KM: return METERS_PER_KM; case UnitsDistanceCount: break; } return 1; } const char *health_util_get_distance_string(const char *miles_string, const char *km_string) { switch (shell_prefs_get_units_distance()) { case UnitsDistance_Miles: return miles_string; case UnitsDistance_KM: return km_string; case UnitsDistanceCount: break; } return ""; } int health_util_format_distance(char *buffer, size_t buffer_size, uint32_t distance_m) { return health_util_format_whole_and_decimal(buffer, buffer_size, distance_m, health_util_get_distance_factor()); } void health_util_convert_distance_to_whole_and_decimal_part(int distance_m, int *whole_part, int *decimal_part) { const int conversion_factor = health_util_get_distance_factor(); health_util_convert_fraction_to_whole_and_decimal_part(distance_m, conversion_factor, whole_part, decimal_part); } time_t health_util_get_pace(int time_s, int distance_meter) { if (!distance_meter) { return 0; } return ROUND(time_s * health_util_get_distance_factor(), distance_meter); } <|fim_middle|>health_util_create_text_node(hours_and_minutes_buffer_size, number_font, color, container)<|endoftext|>
masked_node
call_expression
src/fw/services/normal/comm_session/app_session_capabilities.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "process_management/app_install_types.h" #include "process_management/app_manager.h" #include "services/common/comm_session/app_session_capabilities.h" #include "services/normal/settings/settings_file.h" #include "util/units.h" #define APP_SESSION_CAPABILITIES_CACHE_FILENAME "app_comm" #define APP_SESSION_CAPABILITIES_CACHE_FILE_MAX_USED_SPACE (KiBYTES(2)) static status_t prv_open(SettingsFile *settings_file) { return settings_file_open(settings_file, APP_SESSION_CAPABILITIES_CACHE_FILENAME, APP_SESSION_CAPABILITIES_CACHE_FILE_MAX_USED_SPACE); } bool comm_session_current_app_session_cache_has_capability(CommSessionCapability capability) { CommSession *app_session = comm_session_get_current_app_session(); const Uuid app_uuid = app_manager_get_current_app_md()->uuid; SettingsFile settings_file; status_t open_status = prv_open(&settings_file); uint64_t cached_capabilities = 0; if (PASSED(open_status)) { settings_file_get(&settings_file, &app_uuid, sizeof(app_uuid), &cached_capabilities, sizeof(cached_capabilities)); } uint64_t new_capabilities = cached_capabilities; if (app_session) { // Connected, grab fresh capabilities data: new_capabilities = comm_session_get_capabilities(app_session); if (FAILED(open_status)) { // File open failed, return live data without saving to cache goto done; } if (new_capabilities != cached_capabilities) { settings_file_set(&settings_file, &app_uuid, sizeof(app_uuid), &new_capabilities, sizeof(new_capabilities)); } } else { // Not connected, use cached data. if (FAILED(open_status)) { // File open failed, no cache available goto done; } } settings_file_close(&settings_file); done: return ((new_capabilities & capability) != 0); } static void prv_rewrite_cb(SettingsFile *old_file, SettingsFile *new_file, SettingsRecordInfo *info, void *context) { if (!info->val_len) { return; // Cache for this app has been deleted, don't rewrite it } Uuid key; uint64_t val; info->get_key(old_file, &key, sizeof(key)); info->get_val(old_file, &val, sizeof(val)); settings_file_set(new_file, &key, sizeof(key), &val, sizeof(val)); } void comm_session_app_session_capabilities_evict(const Uuid *app_uuid) { SettingsFile settings_file; if (PASSED(prv_open(&settings_file))) {
; settings_file_close(&settings_file); } } void comm_session_app_session_capabilities_init(void) { SettingsFile settings_file; if (PASSED(prv_open(&settings_file))) { settings_file_rewrite(&settings_file, prv_rewrite_cb, NULL); settings_file_close(&settings_file); } }
settings_file_delete(&settings_file, app_uuid, sizeof(*app_uuid))
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/comm_session/app_session_capabilities.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "process_management/app_install_types.h" #include "process_management/app_manager.h" #include "services/common/comm_session/app_session_capabilities.h" #include "services/normal/settings/settings_file.h" #include "util/units.h" #define APP_SESSION_CAPABILITIES_CACHE_FILENAME "app_comm" #define APP_SESSION_CAPABILITIES_CACHE_FILE_MAX_USED_SPACE (KiBYTES(2)) static status_t prv_open(SettingsFile *settings_file) { return settings_file_open(settings_file, APP_SESSION_CAPABILITIES_CACHE_FILENAME, APP_SESSION_CAPABILITIES_CACHE_FILE_MAX_USED_SPACE); } bool comm_session_current_app_session_cache_has_capability(CommSessionCapability capability) { CommSession *app_session = comm_session_get_current_app_session(); const Uuid app_uuid = app_manager_get_current_app_md()->uuid; SettingsFile settings_file; status_t open_status = prv_open(&settings_file); uint64_t cached_capabilities = 0; if (PASSED(open_status)) { settings_file_get(&settings_file, &app_uuid, sizeof(app_uuid), &cached_capabilities, sizeof(cached_capabilities)); } uint64_t new_capabilities = cached_capabilities; if (app_session) { // Connected, grab fresh capabilities data: new_capabilities = comm_session_get_capabilities(app_session); if (FAILED(open_status)) { // File open failed, return live data without saving to cache goto done; } if (new_capabilities != cached_capabilities) { settings_file_set(&settings_file, &app_uuid, sizeof(app_uuid), &new_capabilities, sizeof(new_capabilities)); } } else { // Not connected, use cached data. if (FAILED(open_status)) { // File open failed, no cache available goto done; } } settings_file_close(&settings_file); done: return ((new_capabilities & capability) != 0); } static void prv_rewrite_cb(SettingsFile *old_file, SettingsFile *new_file, SettingsRecordInfo *info, void *context) { if (!info->val_len) { return; // Cache for this app has been deleted, don't rewrite it } Uuid key; uint64_t val; info->get_key(old_file, &key, sizeof(key)); info->get_val(old_file, &val, sizeof(val)); settings_file_set(new_file, &key, sizeof(key), &val, sizeof(val)); } void comm_session_app_session_capabilities_evict(const Uuid *app_uuid) { SettingsFile settings_file; if (PASSED(prv_open(&settings_file))) { <|fim_suffix|>; settings_file_close(&settings_file); } } void comm_session_app_session_capabilities_init(void) { SettingsFile settings_file; if (PASSED(prv_open(&settings_file))) { settings_file_rewrite(&settings_file, prv_rewrite_cb, NULL); settings_file_close(&settings_file); } } <|fim_middle|>settings_file_delete(&settings_file, app_uuid, sizeof(*app_uuid))<|endoftext|>
masked_node
compound_statement
tests/libc/printf/test_sprintf.c
"aaaa aaaa aaaa aaaa " // 20- 40 "aaaa aaaa aaaa aaaa " // 40- 60 "aaaa aaaa aaaa aaaa " // 60- 80 "aaaa aaaa aaaa aaaa " // 80-100 "aaaa aaaa aaaa aaaa " //100-120 "aaaa aaaa aaaa aaaa " //120-140 "aaaa aaaa aaaa aaaa " //140-160 "aaaa aaaa aaaa aaaa " //160-180 "aaaa aaaa aaaa aaaa " //180-200 "aaaa aaaa aaaa aaaa " //200-220 "aaaa aaaa aaaa aaaa " //220-240 "aaaa aaaa aaaa aaaa " //240-260 "aaaa aaaa aaaa aaaa " //260-280 "%llnaaaa aaaa aaaa aaaa " //280-300 "aaaa aaaa aaaa aaaa " //300-320 , llntest); cl_assert_equal_i(llntest[0], 280); cl_assert_equal_i(llntest[1], 0); jntest[0] = jntest[1] = 0; snprintf(dstbuf, 512, "aaaa aaaa aaaa aaaa " // 0- 20 "aaaa aaaa aaaa aaaa " // 20- 40 "aaaa aaaa aaaa aaaa " // 40- 60 "aaaa aaaa aaaa aaaa " // 60- 80 "aaaa aaaa aaaa aaaa " // 80-100 "aaaa aaaa aaaa aaaa " //100-120 "aaaa aaaa aaaa aaaa " //120-140 "aaaa aaaa aaaa aaaa " //140-160 "aaaa aaaa aaaa aaaa " //160-180 "aaaa aaaa aaaa aaaa " //180-200 "aaaa aaaa aaaa aaaa " //200-220 "aaaa aaaa aaaa aaaa " //220-240 "aaaa aaaa aaaa aaaa " //240-260 "aaaa aaaa aaaa aaaa " //260-280 "%jnaaaa aaaa aaaa aaaa " //280-300 "aaaa aaaa aaaa aaaa " //300-320 , jntest); cl_assert_equal_i(jntest[0], 280); cl_assert_equal_i(jntest[1], 0); zntest[0] = zntest[1] = 0; snprintf(dstbuf, 512, "aaaa aaaa aaaa aaaa " // 0- 20 "aaaa aaaa aaaa aaaa " // 20- 40 "aaaa aaaa aaaa aaaa " // 40- 60 "aaaa aaaa aaaa aaaa " // 60- 80 "aaaa aaaa aaaa aaaa " // 80-100 "aaaa aaaa aaaa aaaa " //100-120 "aaaa aaaa aaaa aaaa " //120-140 "aaaa aaaa aaaa aaaa " //140-160 "aaaa aaaa aaaa aaaa " //160-180 "aaaa aaaa aaaa aaaa " //180-200 "aaaa aaaa aaaa aaaa " //200-220 "aaaa aaaa aaaa aaaa " //220-240 "aaaa aaaa aaaa aaaa " //240-260 "aaaa aaaa aaaa aaaa " //260-280 "%znaaaa aaaa aaaa aaaa " //280-300 "aaaa aaaa aaaa aaaa " //300-320 , zntest); cl_assert_equal_i(zntest[0], 280); cl_assert_equal_i(zntest[1], 0); tntest[0] = tntest[1] = 0; snprintf(dstbuf, 512, "aaaa aaaa aaaa aaaa " // 0- 20 "aaaa aaaa aaaa aaaa " // 20- 40 "aaaa aaaa aaaa aaaa " // 40- 60 "aaaa aaaa aaaa aaaa " // 60- 80 "aaaa aaaa aaaa aaaa " // 80-100 "aaaa aaaa aaaa aaaa " //100-120 "aaaa aaaa aaaa aaaa " //120-140 "aaaa aaaa aaaa aaaa " //140-160 "aaaa aaaa aaaa aaaa " //160-180 "aaaa aaaa aaaa aaaa " //180-200 "aaaa aaaa aaaa aaaa " //200-220 "aaaa aaaa aaaa aaaa " //220-240 "aaaa aaaa aaaa aaaa " //240-260 "aaaa aaaa aaaa aaaa " //260-280 "%tnaaaa aaaa aaaa aaaa " //280-300 "aaaa aaaa aaaa aaaa " //300-320 , tntest); cl_assert_equal_i(tntest[0], 280);
cl_assert_equal_i(tntest[1], 0); }
<|repo_name|>pebble <|file_sep|>tests/libc/printf/test_sprintf.c <|fim_prefix|> "aaaa aaaa aaaa aaaa " // 20- 40 "aaaa aaaa aaaa aaaa " // 40- 60 "aaaa aaaa aaaa aaaa " // 60- 80 "aaaa aaaa aaaa aaaa " // 80-100 "aaaa aaaa aaaa aaaa " //100-120 "aaaa aaaa aaaa aaaa " //120-140 "aaaa aaaa aaaa aaaa " //140-160 "aaaa aaaa aaaa aaaa " //160-180 "aaaa aaaa aaaa aaaa " //180-200 "aaaa aaaa aaaa aaaa " //200-220 "aaaa aaaa aaaa aaaa " //220-240 "aaaa aaaa aaaa aaaa " //240-260 "aaaa aaaa aaaa aaaa " //260-280 "%llnaaaa aaaa aaaa aaaa " //280-300 "aaaa aaaa aaaa aaaa " //300-320 , llntest); cl_assert_equal_i(llntest[0], 280); cl_assert_equal_i(llntest[1], 0); jntest[0] = jntest[1] = 0; snprintf(dstbuf, 512, "aaaa aaaa aaaa aaaa " // 0- 20 "aaaa aaaa aaaa aaaa " // 20- 40 "aaaa aaaa aaaa aaaa " // 40- 60 "aaaa aaaa aaaa aaaa " // 60- 80 "aaaa aaaa aaaa aaaa " // 80-100 "aaaa aaaa aaaa aaaa " //100-120 "aaaa aaaa aaaa aaaa " //120-140 "aaaa aaaa aaaa aaaa " //140-160 "aaaa aaaa aaaa aaaa " //160-180 "aaaa aaaa aaaa aaaa " //180-200 "aaaa aaaa aaaa aaaa " //200-220 "aaaa aaaa aaaa aaaa " //220-240 "aaaa aaaa aaaa aaaa " //240-260 "aaaa aaaa aaaa aaaa " //260-280 "%jnaaaa aaaa aaaa aaaa " //280-300 "aaaa aaaa aaaa aaaa " //300-320 , jntest); cl_assert_equal_i(jntest[0], 280); cl_assert_equal_i(jntest[1], 0); zntest[0] = zntest[1] = 0; snprintf(dstbuf, 512, "aaaa aaaa aaaa aaaa " // 0- 20 "aaaa aaaa aaaa aaaa " // 20- 40 "aaaa aaaa aaaa aaaa " // 40- 60 "aaaa aaaa aaaa aaaa " // 60- 80 "aaaa aaaa aaaa aaaa " // 80-100 "aaaa aaaa aaaa aaaa " //100-120 "aaaa aaaa aaaa aaaa " //120-140 "aaaa aaaa aaaa aaaa " //140-160 "aaaa aaaa aaaa aaaa " //160-180 "aaaa aaaa aaaa aaaa " //180-200 "aaaa aaaa aaaa aaaa " //200-220 "aaaa aaaa aaaa aaaa " //220-240 "aaaa aaaa aaaa aaaa " //240-260 "aaaa aaaa aaaa aaaa " //260-280 "%znaaaa aaaa aaaa aaaa " //280-300 "aaaa aaaa aaaa aaaa " //300-320 , zntest); cl_assert_equal_i(zntest[0], 280); cl_assert_equal_i(zntest[1], 0); tntest[0] = tntest[1] = 0; snprintf(dstbuf, 512, "aaaa aaaa aaaa aaaa " // 0- 20 "aaaa aaaa aaaa aaaa " // 20- 40 "aaaa aaaa aaaa aaaa " // 40- 60 "aaaa aaaa aaaa aaaa " // 60- 80 "aaaa aaaa aaaa aaaa " // 80-100 "aaaa aaaa aaaa aaaa " //100-120 "aaaa aaaa aaaa aaaa " //120-140 "aaaa aaaa aaaa aaaa " //140-160 "aaaa aaaa aaaa aaaa " //160-180 "aaaa aaaa aaaa aaaa " //180-200 "aaaa aaaa aaaa aaaa " //200-220 "aaaa aaaa aaaa aaaa " //220-240 "aaaa aaaa aaaa aaaa " //240-260 "aaaa aaaa aaaa aaaa " //260-280 "%tnaaaa aaaa aaaa aaaa " //280-300 "aaaa aaaa aaaa aaaa " //300-320 , tntest); cl_assert_equal_i(tntest[0], 280); <|fim_suffix|> <|fim_middle|> cl_assert_equal_i(tntest[1], 0); }<|endoftext|>
prefix_only
call_expression
tests/libutil/test_math.c
check_atan2(1, -32768); // <- causes overflow for int16 check_atan2(20001, 20000); // <- causes overflow if numbers are added in an int16 check_atan2(32767, 1); check_atan2(1, 32767); check_atan2(32767, 0); check_atan2(0, 32767); check_atan2(23400, -25300); check_atan2(30500, -1930); check_atan2(-6, -310); check_atan2(15000, -19); check_atan2(34, -3200); check_atan2(-1508, 299); check_atan2(1020, 1002); } void test_math__ceil_log_two(void) { check_ceil_log_two(4); check_ceil_log_two(5); check_ceil_log_two(100); check_ceil_log_two(256); check_ceil_log_two(123456); } void test_math__sign_extend(void) { cl_assert_equal_i(sign_extend(0, 32), 0); cl_assert_equal_i(sign_extend(0, 3), 0); cl_assert_equal_i(sign_extend(1, 32), 1); cl_assert_equal_i(sign_extend(1, 3), 1); cl_assert_equal_i(sign_extend(-1, 32), -1); cl_assert_equal_i(sign_extend(-1, 3), -1); cl_assert_equal_i(sign_extend(7, 32), 7); cl_assert_equal_i(sign_extend(7, 3), -1); } void test_math__serial_distance32(void) { { int32_t dist = serial_distance32(0x0, 0x1); cl_assert_equal_i(dist, 1); } { int32_t dist = serial_distance32(0x1, 0x0); cl_assert_equal_i(dist, -1); } { int32_t dist = serial_distance32(0x0, 0xffffffff); cl_assert_equal_i(dist, -1); } { int32_t dist = serial_distance32(0xffffffff, 0x0); cl_assert_equal_i(dist, 1); } { int32_t dist = serial_distance32(0x0, 0x7fffffff); cl_assert_equal_i(dist, 0x7fffffff); } } void test_math__serial_distance3(void) { { int32_t dist = serial_distance(0, 1, 3); cl_assert_equal_i(dist, 1); } { int32_t dist = serial_distance(1, 0, 3); cl_assert_equal_i(dist, -1); } { int32_t dist = serial_distance(0, 7, 3); cl_assert_equal_i(dist, -1); } { int32_t dist = serial_distance(7, 0, 3); cl_assert_equal_i(dist, 1); } { int32_t dist = serial_distance(6, 0, 3); cl_assert_equal_i(dist, 2); } { int32_t dist = serial_distance(7, 1, 3); cl_assert_equal_i(dist, 2); } { int32_t dist = serial_distance(6, 1, 3); cl_assert_equal_i(dist, 3); } } void test_math__is_signed_macro(void) { cl_assert(IS_SIGNED((int)-1) == true); cl_assert(IS_SIGNED((unsigned int)1) == false); } void test_math__test_within_macro(void) { int16_t min; int16_t max; // Min and max are both positive //////////////////////////////// min = 5; max = 10; // Min and max themselves should satisfy WITHIN cl_assert_equal_b(WITHIN(min, min, max), true); cl_assert_equal_b(WITHIN(max, min, max), true); // In the middle of the bounds cl_assert_equal_b(WITHIN(7, min, max), true); // Just out of bounds cl_assert_equal_b(WITHIN(4, min, max), false); cl_assert_equal_b(WITHIN(11, min, max), false); // Negative out of bounds cl_assert_equal_i(WITHIN(-5, min, max), false); // Positive out of bounds cl_assert_equal_i(WITHIN(0, min, max), false); // Min negative, max positive //////////////////////////////// min = -10; max = 10; // Min and max themselves should satisfy WITHIN cl_assert_equal_b(WITHIN(min, min, max), true); cl_assert_equal_b(WITHIN(max, min, max), true); // In the middle of the bounds cl_assert_equal_i(WITHIN(-5, min, max), true); cl_assert_equal_i(WITHIN(0, min, max), true); cl_assert_equal_i(WITHIN(5, min, max), true); // Just out of bounds cl_assert_equal_i(WITHIN(-11, min, max), false); cl_assert_equal_i(WITHIN(11, min, max), false); // Min and max are both negative //////////////////////////////// min = -20; max = -10; // Min and max themselves should satisfy WITHIN cl_assert_equal_b(WITHIN(min, min, max), true); cl_assert_equal_b(WITHIN(max, min, max), true); // In the middle of the bounds cl_assert_equal_i(WITHIN(-15, min, max), true); // Just out of bounds cl_assert_equal_i(WITHIN(-21, min, max), false); cl_assert_equal_i(WITHIN(-9, min, max), false); // Positive out of bounds cl_assert_equal_i(WITHIN(0, min, max), false); cl_assert_equal_i(
WITHIN(5, min, max)
<|repo_name|>pebble <|file_sep|>tests/libutil/test_math.c <|fim_prefix|> check_atan2(1, -32768); // <- causes overflow for int16 check_atan2(20001, 20000); // <- causes overflow if numbers are added in an int16 check_atan2(32767, 1); check_atan2(1, 32767); check_atan2(32767, 0); check_atan2(0, 32767); check_atan2(23400, -25300); check_atan2(30500, -1930); check_atan2(-6, -310); check_atan2(15000, -19); check_atan2(34, -3200); check_atan2(-1508, 299); check_atan2(1020, 1002); } void test_math__ceil_log_two(void) { check_ceil_log_two(4); check_ceil_log_two(5); check_ceil_log_two(100); check_ceil_log_two(256); check_ceil_log_two(123456); } void test_math__sign_extend(void) { cl_assert_equal_i(sign_extend(0, 32), 0); cl_assert_equal_i(sign_extend(0, 3), 0); cl_assert_equal_i(sign_extend(1, 32), 1); cl_assert_equal_i(sign_extend(1, 3), 1); cl_assert_equal_i(sign_extend(-1, 32), -1); cl_assert_equal_i(sign_extend(-1, 3), -1); cl_assert_equal_i(sign_extend(7, 32), 7); cl_assert_equal_i(sign_extend(7, 3), -1); } void test_math__serial_distance32(void) { { int32_t dist = serial_distance32(0x0, 0x1); cl_assert_equal_i(dist, 1); } { int32_t dist = serial_distance32(0x1, 0x0); cl_assert_equal_i(dist, -1); } { int32_t dist = serial_distance32(0x0, 0xffffffff); cl_assert_equal_i(dist, -1); } { int32_t dist = serial_distance32(0xffffffff, 0x0); cl_assert_equal_i(dist, 1); } { int32_t dist = serial_distance32(0x0, 0x7fffffff); cl_assert_equal_i(dist, 0x7fffffff); } } void test_math__serial_distance3(void) { { int32_t dist = serial_distance(0, 1, 3); cl_assert_equal_i(dist, 1); } { int32_t dist = serial_distance(1, 0, 3); cl_assert_equal_i(dist, -1); } { int32_t dist = serial_distance(0, 7, 3); cl_assert_equal_i(dist, -1); } { int32_t dist = serial_distance(7, 0, 3); cl_assert_equal_i(dist, 1); } { int32_t dist = serial_distance(6, 0, 3); cl_assert_equal_i(dist, 2); } { int32_t dist = serial_distance(7, 1, 3); cl_assert_equal_i(dist, 2); } { int32_t dist = serial_distance(6, 1, 3); cl_assert_equal_i(dist, 3); } } void test_math__is_signed_macro(void) { cl_assert(IS_SIGNED((int)-1) == true); cl_assert(IS_SIGNED((unsigned int)1) == false); } void test_math__test_within_macro(void) { int16_t min; int16_t max; // Min and max are both positive //////////////////////////////// min = 5; max = 10; // Min and max themselves should satisfy WITHIN cl_assert_equal_b(WITHIN(min, min, max), true); cl_assert_equal_b(WITHIN(max, min, max), true); // In the middle of the bounds cl_assert_equal_b(WITHIN(7, min, max), true); // Just out of bounds cl_assert_equal_b(WITHIN(4, min, max), false); cl_assert_equal_b(WITHIN(11, min, max), false); // Negative out of bounds cl_assert_equal_i(WITHIN(-5, min, max), false); // Positive out of bounds cl_assert_equal_i(WITHIN(0, min, max), false); // Min negative, max positive //////////////////////////////// min = -10; max = 10; // Min and max themselves should satisfy WITHIN cl_assert_equal_b(WITHIN(min, min, max), true); cl_assert_equal_b(WITHIN(max, min, max), true); // In the middle of the bounds cl_assert_equal_i(WITHIN(-5, min, max), true); cl_assert_equal_i(WITHIN(0, min, max), true); cl_assert_equal_i(WITHIN(5, min, max), true); // Just out of bounds cl_assert_equal_i(WITHIN(-11, min, max), false); cl_assert_equal_i(WITHIN(11, min, max), false); // Min and max are both negative //////////////////////////////// min = -20; max = -10; // Min and max themselves should satisfy WITHIN cl_assert_equal_b(WITHIN(min, min, max), true); cl_assert_equal_b(WITHIN(max, min, max), true); // In the middle of the bounds cl_assert_equal_i(WITHIN(-15, min, max), true); // Just out of bounds cl_assert_equal_i(WITHIN(-21, min, max), false); cl_assert_equal_i(WITHIN(-9, min, max), false); // Positive out of bounds cl_assert_equal_i(WITHIN(0, min, max), false); cl_assert_equal_i(<|fim_suffix|><|fim_middle|>WITHIN(5, min, max)<|endoftext|>
masked_node
argument_list
tests/fw/services/test_pfs.c
ce Avail = %d\n", bytes_available); uint8_t *bigbuf = (uint8_t *)calloc(large_file_size, 1); uint16_t curr = 0; for (int i = 0; i < 2; i++) { snprintf(file_large, sizeof(file_large), "large%d", i); for (int i = 0; i < large_file_size / 4; i++) { *(((uint32_t *)((uint8_t *)bigbuf)) + i) = curr | (curr << 16); curr++; } int fd = pfs_open(file_large, OP_FLAG_WRITE, FILE_TYPE_STATIC, large_file_size); printf("the fd is: %d\n", fd); cl_assert(fd >= 0); cl_assert(pfs_write(fd, bigbuf, large_file_size) == large_file_size); cl_assert(pfs_close(fd) == S_SUCCESS); } free(bigbuf); // now read back the large files curr = 0; for (int i = 0; i < 2; i++) { snprintf(file_large, sizeof(file_large), "large%d", i); int fd = pfs_open(file_large, OP_FLAG_READ, 0, 0); cl_assert(fd >= 0); size_t sz = pfs_get_file_size(fd); cl_assert(sz == large_file_size); uint8_t *b = calloc(sz, 1); cl_assert(pfs_read(fd, b, sz) == sz); for (int j = 0; j < large_file_size / 4; j++) { uint32_t *val = ((uint32_t *)((uint8_t *)b)) + j; cl_assert(*val == (curr | (curr << 16))); curr++; } cl_assert(pfs_close(fd) == S_SUCCESS); free(b); } } void test_pfs__file_span_regions(void) { pfs_format(false /* write erase headers */); // start with an empty flash pfs_init(false); char name[128]; snprintf(name, sizeof(name), "bigfile"); //Fill up entire memory section, subtract 32768 for header space. int fd = pfs_open(name, OP_FLAG_WRITE, FILE_TYPE_STATIC, pfs_get_size() - (num_pages()*128)); printf("%d\n", pfs_get_size() - 1024); cl_assert(fd >= 0); cl_assert(pfs_close(fd) == S_SUCCESS); cl_assert(pfs_remove(name) == S_SUCCESS); } void test_pfs__active_regions(void) { pfs_format(false); cl_assert(!pfs_active_in_region(0, pfs_get_size())); // erase every page and make sure pfs is active pfs_format(true); cl_assert(pfs_active_in_region(0, pfs_get_size())); // write something on every page and make sure pfs is active char file_name[10]; for (int i = 0; i < num_pages(); i++) { snprintf(file_name, sizeof(file_name), "file%d", i); int fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10); cl_assert(fd >= 0); cl_assert(pfs_close(fd) == S_SUCCESS); } cl_assert(pfs_active_in_region(0, pfs_get_size())); // delete every page and make sure pfs is active for (int i = 0; i < num_pages(); i++) { snprintf(file_name, sizeof(file_name), "file%d", i); cl_assert(pfs_remove(file_name) == S_SUCCESS); } cl_assert(pfs_active_in_region(0, pfs_get_size())); // continuation page on region and make sure pfs is active pfs_format(true); int fd = pfs_open("testfile", OP_FLAG_WRITE, FILE_TYPE_STATIC, 68000); cl_assert(fd >= 0); cl_assert(pfs_close(fd) == S_SUCCESS); cl_assert(pfs_active_in_region(32000, 68000)); } int run_full_flash_region_test(void) { char name[128]; // assumes # pages is a multiple of 2 int st_val = 0; const int f_size = (((PFS_SECTOR_SIZE * 2) - 400) / sizeof(st_val)) * sizeof(st_val); int num_vals = f_size / sizeof(st_val); int idx = 0; int fd, rv; while (true) { snprintf(name, sizeof(name), "file%d", idx); if ((fd = pfs_open(name, OP_FLAG_WRITE, FILE_TYPE_STATIC, f_size)) < 0) { break; } for (int i = 0; i < num_vals; i++) { st_val = st_val + i; rv = pfs_write(fd, (uint8_t *)&st_val, sizeof(st_val)); cl_assert_equal_i(rv, sizeof(st_val)); } pfs_close(fd); idx++; } cl_assert_equal_i((status_t)fd, E_OUT_OF_STORAGE); // read back files to make sure they are all correct st_val = 0; for (int i = 0; i < idx; i++) { snprintf(name, sizeof(name), "file%d", i); if ((fd = pfs_open(name, OP_FLAG_READ, FILE_TYPE_STATIC, f_size)) < 0) { break; } for (int j = 0; j < num_vals; j++) { st_val = st_val + j; int out_val; rv = pfs_read(fd, (uint8_t *)&out_val, sizeof(out_val)); cl_assert_equal_i(rv, sizeof(st_val)); cl_assert_equal_i
; } pfs_close(fd); } return (idx); } void test_pfs__out_of_space(void) { pfs_format(false /* write erase headers */); // start with an empty flash pfs_init(false); int num_iters = 30; for (int i = 0; i < num_iters; i++) { int files_written = run_full_flash_region_test(); if ((i % 2) == 0) { pfs_init(true); // simulate a reboot } // delete all files for (int i = (files_written - 1); i >= 0; i--) { char name[128]; snprintf(name, sizeof(name), "file%d", i); cl_assert_equal_i(pfs_remove(name), S_SUCCESS); } } } void test_pfs__active_in_region(void) { cl_assert(pfs_active_in_region(0, pfs_get_size())); } void test_pfs__get_size(void) { cl_assert(pfs_get_size() == (ftl_get_size() - SECTOR_SIZE_BYTES)); } void test_pfs__migration(void) { // reset the flash fake_spi_flash_cleanup(); fake_spi_flash_init(0, 0x1000000); extern void ftl_force_version(int version_idx); pfs_init(true); ftl_force_version(1); // simulate a migration by leaving leaving files in various states // in the first region. Then try to add another region and confirm // none of the files have been corrupted char file_small[10]; char buf[50]; const int erase_count = 3; for (int num_erases = 0; num_erases < erase_count; num_erases++) { for (int i = 0; i < num_pages(); i++) { snprintf(file_small, sizeof(file_small), "file%d", i); snprintf(buf, sizeof(buf), "This is small buf %d!", i); int len = strlen(buf); int fd = pfs_open(file_small, OP_FLAG_WRITE, FILE_TYPE_STATIC, len); cl_assert(fd >= 0); cl_assert(pfs_write(fd, (uint8_t *)buf, len) == len); cl_assert(pfs_close(fd) == S_SUCCESS); if (num_erases != (erase_count - 1)) { cl_assert(pfs_remove(file_small) == S_SUCCESS); } } } int original_page_count = num_pages(); ftl_populate_region_list(); // make sure something was added PBL_LOG(LOG_LEVEL_DEBUG, "original pages %u, num pages: %u", original_page_count, num_pages()); cl_assert(original_page_count < num_pages()); for (int i = 0; i < original_page_count; i++) { snprintf(file_small, sizeof(file_small), "file%d", i); snprintf(buf, sizeof(buf), "This is small buf %d!", i); int len = strlen(buf); char rbuf[len]; int fd = pfs_open(file_small, OP_FLAG_READ, FILE_TYPE_STATIC, 0); cl_assert(fd >= 0); cl_assert_equal_i(pfs_read(fd, (uint8_t *)rbuf, len), len); cl_assert(memcmp(rbuf, buf, len) == 0); cl_assert(fd >= 0); cl_assert(pfs_close(fd) == S_SUCCESS); } } static uint32_t s_watch_file_callback_called_count = 0; static void prv_file_changed_callback(void *data) { s_watch_file_callback_called_count++; } void test_pfs__watch_file_callbacks(void) { const char* file_name = "newfile"; PFSCallbackHandle cb_handle = pfs_watch_file(file_name, prv_file_changed_callback, FILE_CHANGED_EVENT_ALL, NULL); // Callback should get invoked if we close with write access s_watch_file_callback_called_count = 0; int fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10); cl_assert(fd >= 0); pfs_close(fd); cl_assert(s_watch_file_callback_called_count == 1); // Callback should not get invoked if we close with read access s_watch_file_callback_called_count = 0; fd = pfs_open(file_name, OP_FLAG_READ, 0, 0); cl_assert(fd >= 0); pfs_close(fd); cl_assert(s_watch_file_callback_called_count == 0); // Callback should get invoked if we remove the file s_watch_file_callback_called_count = 0; pfs_remove(file_name); cl_assert(s_watch_file_callback_called_count == 1); pfs_unwatch_file(cb_handle); // Callback should not get invoked anymore s_watch_file_callback_called_count = 0; fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10); cl_assert(fd >= 0); pfs_close(fd); cl_assert(s_watch_file_callback_called_count == 0); } extern status_t test_scan_for_last_written(void); void test_pfs__last_written_page(void) { pfs_format(true); pfs_init(false
(out_val, st_val)
<|repo_name|>pebble <|file_sep|>tests/fw/services/test_pfs.c <|fim_prefix|>ce Avail = %d\n", bytes_available); uint8_t *bigbuf = (uint8_t *)calloc(large_file_size, 1); uint16_t curr = 0; for (int i = 0; i < 2; i++) { snprintf(file_large, sizeof(file_large), "large%d", i); for (int i = 0; i < large_file_size / 4; i++) { *(((uint32_t *)((uint8_t *)bigbuf)) + i) = curr | (curr << 16); curr++; } int fd = pfs_open(file_large, OP_FLAG_WRITE, FILE_TYPE_STATIC, large_file_size); printf("the fd is: %d\n", fd); cl_assert(fd >= 0); cl_assert(pfs_write(fd, bigbuf, large_file_size) == large_file_size); cl_assert(pfs_close(fd) == S_SUCCESS); } free(bigbuf); // now read back the large files curr = 0; for (int i = 0; i < 2; i++) { snprintf(file_large, sizeof(file_large), "large%d", i); int fd = pfs_open(file_large, OP_FLAG_READ, 0, 0); cl_assert(fd >= 0); size_t sz = pfs_get_file_size(fd); cl_assert(sz == large_file_size); uint8_t *b = calloc(sz, 1); cl_assert(pfs_read(fd, b, sz) == sz); for (int j = 0; j < large_file_size / 4; j++) { uint32_t *val = ((uint32_t *)((uint8_t *)b)) + j; cl_assert(*val == (curr | (curr << 16))); curr++; } cl_assert(pfs_close(fd) == S_SUCCESS); free(b); } } void test_pfs__file_span_regions(void) { pfs_format(false /* write erase headers */); // start with an empty flash pfs_init(false); char name[128]; snprintf(name, sizeof(name), "bigfile"); //Fill up entire memory section, subtract 32768 for header space. int fd = pfs_open(name, OP_FLAG_WRITE, FILE_TYPE_STATIC, pfs_get_size() - (num_pages()*128)); printf("%d\n", pfs_get_size() - 1024); cl_assert(fd >= 0); cl_assert(pfs_close(fd) == S_SUCCESS); cl_assert(pfs_remove(name) == S_SUCCESS); } void test_pfs__active_regions(void) { pfs_format(false); cl_assert(!pfs_active_in_region(0, pfs_get_size())); // erase every page and make sure pfs is active pfs_format(true); cl_assert(pfs_active_in_region(0, pfs_get_size())); // write something on every page and make sure pfs is active char file_name[10]; for (int i = 0; i < num_pages(); i++) { snprintf(file_name, sizeof(file_name), "file%d", i); int fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10); cl_assert(fd >= 0); cl_assert(pfs_close(fd) == S_SUCCESS); } cl_assert(pfs_active_in_region(0, pfs_get_size())); // delete every page and make sure pfs is active for (int i = 0; i < num_pages(); i++) { snprintf(file_name, sizeof(file_name), "file%d", i); cl_assert(pfs_remove(file_name) == S_SUCCESS); } cl_assert(pfs_active_in_region(0, pfs_get_size())); // continuation page on region and make sure pfs is active pfs_format(true); int fd = pfs_open("testfile", OP_FLAG_WRITE, FILE_TYPE_STATIC, 68000); cl_assert(fd >= 0); cl_assert(pfs_close(fd) == S_SUCCESS); cl_assert(pfs_active_in_region(32000, 68000)); } int run_full_flash_region_test(void) { char name[128]; // assumes # pages is a multiple of 2 int st_val = 0; const int f_size = (((PFS_SECTOR_SIZE * 2) - 400) / sizeof(st_val)) * sizeof(st_val); int num_vals = f_size / sizeof(st_val); int idx = 0; int fd, rv; while (true) { snprintf(name, sizeof(name), "file%d", idx); if ((fd = pfs_open(name, OP_FLAG_WRITE, FILE_TYPE_STATIC, f_size)) < 0) { break; } for (int i = 0; i < num_vals; i++) { st_val = st_val + i; rv = pfs_write(fd, (uint8_t *)&st_val, sizeof(st_val)); cl_assert_equal_i(rv, sizeof(st_val)); } pfs_close(fd); idx++; } cl_assert_equal_i((status_t)fd, E_OUT_OF_STORAGE); // read back files to make sure they are all correct st_val = 0; for (int i = 0; i < idx; i++) { snprintf(name, sizeof(name), "file%d", i); if ((fd = pfs_open(name, OP_FLAG_READ, FILE_TYPE_STATIC, f_size)) < 0) { break; } for (int j = 0; j < num_vals; j++) { st_val = st_val + j; int out_val; rv = pfs_read(fd, (uint8_t *)&out_val, sizeof(out_val)); cl_assert_equal_i(rv, sizeof(st_val)); cl_assert_equal_i<|fim_suffix|>; } pfs_close(fd); } return (idx); } void test_pfs__out_of_space(void) { pfs_format(false /* write erase headers */); // start with an empty flash pfs_init(false); int num_iters = 30; for (int i = 0; i < num_iters; i++) { int files_written = run_full_flash_region_test(); if ((i % 2) == 0) { pfs_init(true); // simulate a reboot } // delete all files for (int i = (files_written - 1); i >= 0; i--) { char name[128]; snprintf(name, sizeof(name), "file%d", i); cl_assert_equal_i(pfs_remove(name), S_SUCCESS); } } } void test_pfs__active_in_region(void) { cl_assert(pfs_active_in_region(0, pfs_get_size())); } void test_pfs__get_size(void) { cl_assert(pfs_get_size() == (ftl_get_size() - SECTOR_SIZE_BYTES)); } void test_pfs__migration(void) { // reset the flash fake_spi_flash_cleanup(); fake_spi_flash_init(0, 0x1000000); extern void ftl_force_version(int version_idx); pfs_init(true); ftl_force_version(1); // simulate a migration by leaving leaving files in various states // in the first region. Then try to add another region and confirm // none of the files have been corrupted char file_small[10]; char buf[50]; const int erase_count = 3; for (int num_erases = 0; num_erases < erase_count; num_erases++) { for (int i = 0; i < num_pages(); i++) { snprintf(file_small, sizeof(file_small), "file%d", i); snprintf(buf, sizeof(buf), "This is small buf %d!", i); int len = strlen(buf); int fd = pfs_open(file_small, OP_FLAG_WRITE, FILE_TYPE_STATIC, len); cl_assert(fd >= 0); cl_assert(pfs_write(fd, (uint8_t *)buf, len) == len); cl_assert(pfs_close(fd) == S_SUCCESS); if (num_erases != (erase_count - 1)) { cl_assert(pfs_remove(file_small) == S_SUCCESS); } } } int original_page_count = num_pages(); ftl_populate_region_list(); // make sure something was added PBL_LOG(LOG_LEVEL_DEBUG, "original pages %u, num pages: %u", original_page_count, num_pages()); cl_assert(original_page_count < num_pages()); for (int i = 0; i < original_page_count; i++) { snprintf(file_small, sizeof(file_small), "file%d", i); snprintf(buf, sizeof(buf), "This is small buf %d!", i); int len = strlen(buf); char rbuf[len]; int fd = pfs_open(file_small, OP_FLAG_READ, FILE_TYPE_STATIC, 0); cl_assert(fd >= 0); cl_assert_equal_i(pfs_read(fd, (uint8_t *)rbuf, len), len); cl_assert(memcmp(rbuf, buf, len) == 0); cl_assert(fd >= 0); cl_assert(pfs_close(fd) == S_SUCCESS); } } static uint32_t s_watch_file_callback_called_count = 0; static void prv_file_changed_callback(void *data) { s_watch_file_callback_called_count++; } void test_pfs__watch_file_callbacks(void) { const char* file_name = "newfile"; PFSCallbackHandle cb_handle = pfs_watch_file(file_name, prv_file_changed_callback, FILE_CHANGED_EVENT_ALL, NULL); // Callback should get invoked if we close with write access s_watch_file_callback_called_count = 0; int fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10); cl_assert(fd >= 0); pfs_close(fd); cl_assert(s_watch_file_callback_called_count == 1); // Callback should not get invoked if we close with read access s_watch_file_callback_called_count = 0; fd = pfs_open(file_name, OP_FLAG_READ, 0, 0); cl_assert(fd >= 0); pfs_close(fd); cl_assert(s_watch_file_callback_called_count == 0); // Callback should get invoked if we remove the file s_watch_file_callback_called_count = 0; pfs_remove(file_name); cl_assert(s_watch_file_callback_called_count == 1); pfs_unwatch_file(cb_handle); // Callback should not get invoked anymore s_watch_file_callback_called_count = 0; fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10); cl_assert(fd >= 0); pfs_close(fd); cl_assert(s_watch_file_callback_called_count == 0); } extern status_t test_scan_for_last_written(void); void test_pfs__last_written_page(void) { pfs_format(true); pfs_init(false<|fim_middle|>(out_val, st_val)<|endoftext|>
masked_node
call_expression
src/fw/services/normal/activity/activity_insights.c
int32_t sleep_total_seconds, ActivityScalarStore sleep_average_seconds, Uuid *uuid) { prv_generate_sleep_pin_strings(sleep_enter_seconds, sleep_exit_seconds, sleep_total_seconds); // Insert or update the pin return prv_push_summary_pin(pin_time_utc, now_utc, uuid, sleep_total_seconds, sleep_average_seconds, &SLEEP_SUMMARY_PIN_CONFIG); } // ----------------------------------------------------------------------------------------- static NOINLINE TimelineItem *prv_create_nap_pin(time_t now_utc, ActivitySession *session) { AttributeList pin_attr_list = {}; attribute_list_add_resource_id(&pin_attr_list, AttributeIdIconPin, TIMELINE_RESOURCE_SLEEP); attribute_list_add_uint8(&pin_attr_list, AttributeIdHealthInsightType, ActivityInsightType_ActivitySessionNap); attribute_list_add_uint8(&pin_attr_list, AttributeIdHealthActivityType, ActivitySessionType_Nap); attribute_list_add_uint32(&pin_attr_list, AttributeIdTimestamp, session->start_utc); attribute_list_add_cstring(&pin_attr_list, AttributeIdShortTitle, i18n_get("Nap Time", &pin_attr_list)); // Fits the maximum strings "10H 30M of sleep", "10:00AM - 11:00PM" and i18n variants const size_t max_attr_length = 64; char *elapsed = kernel_zalloc_check(max_attr_length); char *short_subtitle = kernel_zalloc_check(max_attr_length); const uint32_t duration_s = session->length_min * SECONDS_PER_MINUTE; health_util_format_hours_and_minutes(elapsed, max_attr_length, duration_s, &pin_attr_list); const char *short_subtitle_fmt = i18n_get("%s of sleep", &pin_attr_list); /// "10H 30M of sleep" snprintf(short_subtitle, max_attr_length, short_subtitle_fmt, elapsed); attribute_list_add_cstring(&pin_attr_list, AttributeIdShortSubtitle, short_subtitle); attribute_list_add_cstring(&pin_attr_list, AttributeIdSubtitle, elapsed); const char *title_i18n = PBL_IF_RECT_ELSE(i18n_noop("YOU NAPPED"), i18n_noop("Of napping")); attribute_list_add_cstring(&pin_attr_list, PBL_IF_RECT_ELSE(AttributeIdTitle, AttributeIdLocationName), i18n_get(title_i18n, &pin_attr_list)); char *start_time = kernel_zalloc_check(TIME_STRING_TIME_LENGTH); char *end_time = kernel_zalloc_check(TIME_STRING_TIME_LENGTH); char *time_range = kernel_zalloc_check(max_attr_length); const char *time_range_fmt = i18n_get("%s - %s", &pin_attr_list); /// "10:00AM - 11:00PM" clock_copy_time_string_timestamp(start_time, TIME_STRING_TIME_LENGTH, session->start_utc); clock_copy_time_string_timestamp(end_time, TIME_STRING_TIME_LENGTH, session->start_utc + duration_s); snprintf(time_range, max_attr_length, time_range_fmt, start_time, end_time); attribute_list_add_cstring(&pin_attr_list, PBL_IF_RECT_ELSE(AttributeIdLocationName, AttributeIdTitle), time_range); // Don't display the time in the title attribute_list_add_uint8(&pin_attr_list, AttributeIdDisplayTime, WeatherTimeType_None); attribute_list_add_uint32(&pin_attr_list, AttributeIdLastUpdated, now_utc); attribute_list_add_uint8(&pin_attr_list, AttributeIdBgColor, GColorSunsetOrangeARGB8); const int num_responses = 2; ResponseItem *response_items = kernel_zalloc_check(num_responses * sizeof(ResponseItem)); response_items[0] = (ResponseItem) { .type = ActivityInsightResponseTypePositive, .text = i18n_noop("I feel great!"), }; response_items[1] = (ResponseItem) { .type = ActivityInsightResponseTypeNegative, .text = i18n_noop("I need more"), }; TimelineItem *item = prv_create_pin_with_response_items( session->start_utc, now_utc, session->length_min, LayoutIdWeather, &pin_attr_list, HealthCardType_Sleep, num_responses, response_items); kernel_free(response_items); kernel_free(time_range);
; kernel_free(start_time); kernel_free(short_subtitle); kernel_free(elapsed); i18n_free_all(&pin_attr_list); attribute_list_destroy_list(&pin_attr_list); return item; } // ------------------------------------------------------------------------------------------------ // Creates a notification to notify the user of the nap session static void prv_push_nap_session_notification(time_t notif_time, ActivitySession *session, Uuid *pin_uuid) { const int hours = session->length_min / MINUTES_PER_HOUR; const int minutes = session->length_min % MINUTES_PER_HOUR; // Enough to fit the filled out format string below and i18n variants const int max_notif_length = 128; char *body = kernel_malloc_check(max_notif_length); snprintf(body, max_notif_length, i18n_get("Aren't naps great? You knocked out for %dH %dM!", body), hours, minutes); i18n_free_all(body); const NotificationConfig config = { .notif_time = notif_time, .session = session, .insight_type = ActivityInsightType_ActivitySessionNap, .icon_id = TIMELINE_RESOURCE_SLEEP, .body = body, .open_pin = { .enabled = true, .uuid = pin_uuid, }, .response = { .enabled = true, .type = ActivityInsightResponseTypeMisclassified, .title = i18n_noop("I didn't nap!?"), }, }; prv_create_and_push_notification(&config); kernel_free(body); } // ----------------------------------------------------------------------------------------- static void prv_push_nap_session(time_t now_utc, ActivitySession *session) { Uuid pin_uuid = UUID_INVALID; TimelineItem *pin_item = prv_create_nap_pin(now_utc, session); if (prv_push_pin(pin_item, &pin_uuid) && activity_prefs_sleep_insights_are_enabled()) { prv_push_nap_session_notification(now_utc, session, &pin_uuid); } } // ----------------------------------------------------------------------------------------- static void prv_do_nap_session(time_t now_utc, ActivitySession *session) { if (s_nap_pin_state.last_triggered_utc >= session->start_utc) { INSIGHTS_LOG_DEBUG("Not adding nap pin - already added"); return; } s_nap_pin_state.last_triggered_utc = session->start_utc; prv_save_state(ActivitySettingsKeyInsightNapSessionTime, &s_nap_pin_state.last_triggered_utc, sizeof(s_nap_pin_state.last_triggered_utc)); prv_push_nap_session(now_utc, session); } // ----------------------------------------------------------------------------------------- static void prv_do_sleep_notification(time_t now_utc, time_t sleep_exit_utc, int32_t sleep_total_seconds) { if (!activity_prefs_sleep_insights_are_enabled()) { return; } if (s_sleep_pin_state.notified) { INSIGHTS_LOG_DEBUG("Not notifying sleep pin - already notified"); return; } // Notify about the pin after a certain amount of time const time_t since_exited = now_utc - sleep_exit_utc; if (since_exited < s_sleep_summary_settings.summary.sleep.trigger_notif_seconds) { INSIGHTS_LOG_DEBUG("Not notifying sleep pin - not trigger time yet (%ld)", since_exited); return; } // Notify only if they are above the minimum activity since the delay time const int trigger_active_minutes = s_sleep_summary_settings.summary.sleep.trigger_notif_active_minutes; if (s_sleep_pin_state.active_minutes < trigger_active_minutes) { INSIGHTS_LOG_DEBUG("Not notifying sleep pin - not active enough (%d < %d)", s_sleep_pin_state.active_minutes, trigger_active_minutes); return; } s_sleep_pin_state.notified = true; prv_push_sleep_summary_notification(now_utc, sleep_total_seconds, s_sleep_stats.mean, VARIANT_RANDOM); prv_save_state(ActivitySettingsKeyInsightSleepSummaryState, &s_sleep_pin_state, sizeof(s_sleep_pin_state)); } // ----------------------------------------------------------------------------------------- static void prv
kernel_free(end_time)
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/activity/activity_insights.c <|fim_prefix|> int32_t sleep_total_seconds, ActivityScalarStore sleep_average_seconds, Uuid *uuid) { prv_generate_sleep_pin_strings(sleep_enter_seconds, sleep_exit_seconds, sleep_total_seconds); // Insert or update the pin return prv_push_summary_pin(pin_time_utc, now_utc, uuid, sleep_total_seconds, sleep_average_seconds, &SLEEP_SUMMARY_PIN_CONFIG); } // ----------------------------------------------------------------------------------------- static NOINLINE TimelineItem *prv_create_nap_pin(time_t now_utc, ActivitySession *session) { AttributeList pin_attr_list = {}; attribute_list_add_resource_id(&pin_attr_list, AttributeIdIconPin, TIMELINE_RESOURCE_SLEEP); attribute_list_add_uint8(&pin_attr_list, AttributeIdHealthInsightType, ActivityInsightType_ActivitySessionNap); attribute_list_add_uint8(&pin_attr_list, AttributeIdHealthActivityType, ActivitySessionType_Nap); attribute_list_add_uint32(&pin_attr_list, AttributeIdTimestamp, session->start_utc); attribute_list_add_cstring(&pin_attr_list, AttributeIdShortTitle, i18n_get("Nap Time", &pin_attr_list)); // Fits the maximum strings "10H 30M of sleep", "10:00AM - 11:00PM" and i18n variants const size_t max_attr_length = 64; char *elapsed = kernel_zalloc_check(max_attr_length); char *short_subtitle = kernel_zalloc_check(max_attr_length); const uint32_t duration_s = session->length_min * SECONDS_PER_MINUTE; health_util_format_hours_and_minutes(elapsed, max_attr_length, duration_s, &pin_attr_list); const char *short_subtitle_fmt = i18n_get("%s of sleep", &pin_attr_list); /// "10H 30M of sleep" snprintf(short_subtitle, max_attr_length, short_subtitle_fmt, elapsed); attribute_list_add_cstring(&pin_attr_list, AttributeIdShortSubtitle, short_subtitle); attribute_list_add_cstring(&pin_attr_list, AttributeIdSubtitle, elapsed); const char *title_i18n = PBL_IF_RECT_ELSE(i18n_noop("YOU NAPPED"), i18n_noop("Of napping")); attribute_list_add_cstring(&pin_attr_list, PBL_IF_RECT_ELSE(AttributeIdTitle, AttributeIdLocationName), i18n_get(title_i18n, &pin_attr_list)); char *start_time = kernel_zalloc_check(TIME_STRING_TIME_LENGTH); char *end_time = kernel_zalloc_check(TIME_STRING_TIME_LENGTH); char *time_range = kernel_zalloc_check(max_attr_length); const char *time_range_fmt = i18n_get("%s - %s", &pin_attr_list); /// "10:00AM - 11:00PM" clock_copy_time_string_timestamp(start_time, TIME_STRING_TIME_LENGTH, session->start_utc); clock_copy_time_string_timestamp(end_time, TIME_STRING_TIME_LENGTH, session->start_utc + duration_s); snprintf(time_range, max_attr_length, time_range_fmt, start_time, end_time); attribute_list_add_cstring(&pin_attr_list, PBL_IF_RECT_ELSE(AttributeIdLocationName, AttributeIdTitle), time_range); // Don't display the time in the title attribute_list_add_uint8(&pin_attr_list, AttributeIdDisplayTime, WeatherTimeType_None); attribute_list_add_uint32(&pin_attr_list, AttributeIdLastUpdated, now_utc); attribute_list_add_uint8(&pin_attr_list, AttributeIdBgColor, GColorSunsetOrangeARGB8); const int num_responses = 2; ResponseItem *response_items = kernel_zalloc_check(num_responses * sizeof(ResponseItem)); response_items[0] = (ResponseItem) { .type = ActivityInsightResponseTypePositive, .text = i18n_noop("I feel great!"), }; response_items[1] = (ResponseItem) { .type = ActivityInsightResponseTypeNegative, .text = i18n_noop("I need more"), }; TimelineItem *item = prv_create_pin_with_response_items( session->start_utc, now_utc, session->length_min, LayoutIdWeather, &pin_attr_list, HealthCardType_Sleep, num_responses, response_items); kernel_free(response_items); kernel_free(time_range); <|fim_suffix|>; kernel_free(start_time); kernel_free(short_subtitle); kernel_free(elapsed); i18n_free_all(&pin_attr_list); attribute_list_destroy_list(&pin_attr_list); return item; } // ------------------------------------------------------------------------------------------------ // Creates a notification to notify the user of the nap session static void prv_push_nap_session_notification(time_t notif_time, ActivitySession *session, Uuid *pin_uuid) { const int hours = session->length_min / MINUTES_PER_HOUR; const int minutes = session->length_min % MINUTES_PER_HOUR; // Enough to fit the filled out format string below and i18n variants const int max_notif_length = 128; char *body = kernel_malloc_check(max_notif_length); snprintf(body, max_notif_length, i18n_get("Aren't naps great? You knocked out for %dH %dM!", body), hours, minutes); i18n_free_all(body); const NotificationConfig config = { .notif_time = notif_time, .session = session, .insight_type = ActivityInsightType_ActivitySessionNap, .icon_id = TIMELINE_RESOURCE_SLEEP, .body = body, .open_pin = { .enabled = true, .uuid = pin_uuid, }, .response = { .enabled = true, .type = ActivityInsightResponseTypeMisclassified, .title = i18n_noop("I didn't nap!?"), }, }; prv_create_and_push_notification(&config); kernel_free(body); } // ----------------------------------------------------------------------------------------- static void prv_push_nap_session(time_t now_utc, ActivitySession *session) { Uuid pin_uuid = UUID_INVALID; TimelineItem *pin_item = prv_create_nap_pin(now_utc, session); if (prv_push_pin(pin_item, &pin_uuid) && activity_prefs_sleep_insights_are_enabled()) { prv_push_nap_session_notification(now_utc, session, &pin_uuid); } } // ----------------------------------------------------------------------------------------- static void prv_do_nap_session(time_t now_utc, ActivitySession *session) { if (s_nap_pin_state.last_triggered_utc >= session->start_utc) { INSIGHTS_LOG_DEBUG("Not adding nap pin - already added"); return; } s_nap_pin_state.last_triggered_utc = session->start_utc; prv_save_state(ActivitySettingsKeyInsightNapSessionTime, &s_nap_pin_state.last_triggered_utc, sizeof(s_nap_pin_state.last_triggered_utc)); prv_push_nap_session(now_utc, session); } // ----------------------------------------------------------------------------------------- static void prv_do_sleep_notification(time_t now_utc, time_t sleep_exit_utc, int32_t sleep_total_seconds) { if (!activity_prefs_sleep_insights_are_enabled()) { return; } if (s_sleep_pin_state.notified) { INSIGHTS_LOG_DEBUG("Not notifying sleep pin - already notified"); return; } // Notify about the pin after a certain amount of time const time_t since_exited = now_utc - sleep_exit_utc; if (since_exited < s_sleep_summary_settings.summary.sleep.trigger_notif_seconds) { INSIGHTS_LOG_DEBUG("Not notifying sleep pin - not trigger time yet (%ld)", since_exited); return; } // Notify only if they are above the minimum activity since the delay time const int trigger_active_minutes = s_sleep_summary_settings.summary.sleep.trigger_notif_active_minutes; if (s_sleep_pin_state.active_minutes < trigger_active_minutes) { INSIGHTS_LOG_DEBUG("Not notifying sleep pin - not active enough (%d < %d)", s_sleep_pin_state.active_minutes, trigger_active_minutes); return; } s_sleep_pin_state.notified = true; prv_push_sleep_summary_notification(now_utc, sleep_total_seconds, s_sleep_stats.mean, VARIANT_RANDOM); prv_save_state(ActivitySettingsKeyInsightSleepSummaryState, &s_sleep_pin_state, sizeof(s_sleep_pin_state)); } // ----------------------------------------------------------------------------------------- static void prv<|fim_middle|>kernel_free(end_time)<|endoftext|>
prefix_only
argument_list
src/fw/apps/core_apps/spinner_ui_window.c
f 1. // This means that the the lag occurs once less frequently and is less noticable #define LOOPS_PER_ANIMATION 10 #define LOOP_DURATION_MS 1500 static void prv_draw_spinner_circles(Layer *layer, GContext* ctx) { // Drawing the circles with aa is just too slow and we end up backing up the rest of the system. // See PBL-16184 graphics_context_set_antialiased(ctx, false); SpinnerUIData *data = window_get_user_data(layer_get_window(layer)); // This is the background image's circle. #if PLATFORM_ROBERT || PLATFORM_CALCULUS const unsigned int center_of_circle_y_val = 103; #else const unsigned int center_of_circle_y_val = PBL_IF_RECT_ELSE(72, layer->bounds.size.h / 2); #endif const unsigned int radius_of_path = 37; const unsigned int radius_of_spinner_circles = 9; const GPoint circle_center_point = GPoint(layer->bounds.size.w / 2, center_of_circle_y_val); const unsigned int angle = (TRIG_MAX_ANGLE * data->cur_distance_normalized * LOOPS_PER_ANIMATION) / ANIMATION_NORMALIZED_MAX; const GPoint circle1_location = { .x = (sin_lookup(angle) * radius_of_path / TRIG_MAX_RATIO) + circle_center_point.x, .y = (-cos_lookup(angle) * radius_of_path / TRIG_MAX_RATIO) + circle_center_point.y, }; const GPoint circle2_location = { .x = (-sin_lookup(angle) * (-radius_of_path) / TRIG_MAX_RATIO) + circle_center_point.x, .y = (-cos_lookup(angle) * (-radius_of_path) / TRIG_MAX_RATIO) + circle_center_point.y, }; graphics_context_set_fill_color(ctx, data->spinner_color); graphics_context_set_stroke_color(ctx, GColorBlack); graphics_fill_circle(ctx, circle1_location, radius_of_spinner_circles); graphics_draw_circle(ctx, circle1_location, radius_of_spinner_circles); graphics_fill_circle(ctx, circle2_location, radius_of_spinner_circles); graphics_draw_circle(ctx, circle2_location, radius_of_spinner_circles); } static void prv_anim_impl(struct Animation *animation, const AnimationProgress distance_normalized) { SpinnerUIData *data = (SpinnerUIData*) animation_get_context(animation); // We need to artificially limit how frequent we attempt to update the screen. If we update // it too fast the thing we wanted to do in the background never gets done. This isn't quite // ideal, as around 60 steps is when things are actually smooth, but 60 is too fast and does // restrict the speed of our core dump. See PBL-16184 const uint32_t steps_per_loop = 25; const int32_t min_delta = (ANIMATION_NORMALIZED_MAX/LOOPS_PER_ANIMATION) / steps_per_loop; if (data->cur_distance_normalized + min_delta < distance_normalized) { data->cur_distance_normalized = distance_normalized; layer_mark_dirty(&data->anim_layer); } } static void prv_anim_stopped(Animation *animation, bool finished, void *context) { SpinnerUIData *data = (SpinnerUIData*) animation_get_context(animation); if (!data->should_cancel_animation) { data->cur_distance_normalized = 0; animation_schedule(property_animation_get_animation(data->spinner_animation)); } } //////////////////////////////////////////////////////////// // Window loading, unloading, initializing static void prv_window_unload_handler(Window* window) { SpinnerUIData *data = window_get_user_data(window); if (data) { gbitmap_destroy(data->bitmap); data->should_cancel_animation = true; property_animation_destroy(data->spinner_animation); kernel_free(data); } } static void prv_window_load_handler(Window* window) { SpinnerUIData *data = window_get_user_data(window); GRect spinner_bounds = window->layer.bounds; spinner_bounds.origin.y += PBL_IF_RECT_ELSE(0, 10); window_set_background_color(window, PBL_IF_COLOR_ELSE(GColorLightGray, GColorWhite)); BitmapLayer *bitmap_layer = &data->bitmap_layer; bitmap_layer_init(bitmap_layer, &window->layer.bounds); bitmap_layer_set_alignment(bitmap_layer, PBL_IF_RECT_ELSE(GAlignTopLeft, GAlignCenter)); layer_set_frame(&bitmap_layer->layer, &spinner_bounds); data->bitmap = gbitmap_create_with_resource
(RESOURCE_ID_SPINNER_BACKGROUND)
<|repo_name|>pebble <|file_sep|>src/fw/apps/core_apps/spinner_ui_window.c <|fim_prefix|>f 1. // This means that the the lag occurs once less frequently and is less noticable #define LOOPS_PER_ANIMATION 10 #define LOOP_DURATION_MS 1500 static void prv_draw_spinner_circles(Layer *layer, GContext* ctx) { // Drawing the circles with aa is just too slow and we end up backing up the rest of the system. // See PBL-16184 graphics_context_set_antialiased(ctx, false); SpinnerUIData *data = window_get_user_data(layer_get_window(layer)); // This is the background image's circle. #if PLATFORM_ROBERT || PLATFORM_CALCULUS const unsigned int center_of_circle_y_val = 103; #else const unsigned int center_of_circle_y_val = PBL_IF_RECT_ELSE(72, layer->bounds.size.h / 2); #endif const unsigned int radius_of_path = 37; const unsigned int radius_of_spinner_circles = 9; const GPoint circle_center_point = GPoint(layer->bounds.size.w / 2, center_of_circle_y_val); const unsigned int angle = (TRIG_MAX_ANGLE * data->cur_distance_normalized * LOOPS_PER_ANIMATION) / ANIMATION_NORMALIZED_MAX; const GPoint circle1_location = { .x = (sin_lookup(angle) * radius_of_path / TRIG_MAX_RATIO) + circle_center_point.x, .y = (-cos_lookup(angle) * radius_of_path / TRIG_MAX_RATIO) + circle_center_point.y, }; const GPoint circle2_location = { .x = (-sin_lookup(angle) * (-radius_of_path) / TRIG_MAX_RATIO) + circle_center_point.x, .y = (-cos_lookup(angle) * (-radius_of_path) / TRIG_MAX_RATIO) + circle_center_point.y, }; graphics_context_set_fill_color(ctx, data->spinner_color); graphics_context_set_stroke_color(ctx, GColorBlack); graphics_fill_circle(ctx, circle1_location, radius_of_spinner_circles); graphics_draw_circle(ctx, circle1_location, radius_of_spinner_circles); graphics_fill_circle(ctx, circle2_location, radius_of_spinner_circles); graphics_draw_circle(ctx, circle2_location, radius_of_spinner_circles); } static void prv_anim_impl(struct Animation *animation, const AnimationProgress distance_normalized) { SpinnerUIData *data = (SpinnerUIData*) animation_get_context(animation); // We need to artificially limit how frequent we attempt to update the screen. If we update // it too fast the thing we wanted to do in the background never gets done. This isn't quite // ideal, as around 60 steps is when things are actually smooth, but 60 is too fast and does // restrict the speed of our core dump. See PBL-16184 const uint32_t steps_per_loop = 25; const int32_t min_delta = (ANIMATION_NORMALIZED_MAX/LOOPS_PER_ANIMATION) / steps_per_loop; if (data->cur_distance_normalized + min_delta < distance_normalized) { data->cur_distance_normalized = distance_normalized; layer_mark_dirty(&data->anim_layer); } } static void prv_anim_stopped(Animation *animation, bool finished, void *context) { SpinnerUIData *data = (SpinnerUIData*) animation_get_context(animation); if (!data->should_cancel_animation) { data->cur_distance_normalized = 0; animation_schedule(property_animation_get_animation(data->spinner_animation)); } } //////////////////////////////////////////////////////////// // Window loading, unloading, initializing static void prv_window_unload_handler(Window* window) { SpinnerUIData *data = window_get_user_data(window); if (data) { gbitmap_destroy(data->bitmap); data->should_cancel_animation = true; property_animation_destroy(data->spinner_animation); kernel_free(data); } } static void prv_window_load_handler(Window* window) { SpinnerUIData *data = window_get_user_data(window); GRect spinner_bounds = window->layer.bounds; spinner_bounds.origin.y += PBL_IF_RECT_ELSE(0, 10); window_set_background_color(window, PBL_IF_COLOR_ELSE(GColorLightGray, GColorWhite)); BitmapLayer *bitmap_layer = &data->bitmap_layer; bitmap_layer_init(bitmap_layer, &window->layer.bounds); bitmap_layer_set_alignment(bitmap_layer, PBL_IF_RECT_ELSE(GAlignTopLeft, GAlignCenter)); layer_set_frame(&bitmap_layer->layer, &spinner_bounds); data->bitmap = gbitmap_create_with_resource<|fim_suffix|><|fim_middle|>(RESOURCE_ID_SPINNER_BACKGROUND)<|endoftext|>
masked_node
compound_statement
src/fw/drivers/backlight.c
| | | | | | | | // | | | | | | | | // ------- ------- ------- -------- // // The resulting waveform has a frequency of PWM_OUTPUT_FREQUENCY_HZ. Inside each period, the timer // counts up to TIMER_PERIOD_RESOLUTION. This means the counter increments at a rate of // PWM_OUTPUT_FREQUENCY_HZ * TIMER_PERIOD_RESOLUTION, which is the frequency that our timer // prescalar has to calculate. The duty cycle is defined by the TIM_Pulse parameter, which // controls after which counter value the output waveform will become active. For example, a // TIM_Pulse value of TIMER_PERIOD_RESOLUTION / 4 will result in an output waveform that will go // active after 25% of it's period has elapsed. //! The counter reload value. The timer will count from 0 to this value and then reset again. //! The TIM_Pulse member below controls for how many of these counts the resulting PWM signal is //! active for. static const uint32_t TIMER_PERIOD_RESOLUTION = 1024; //! The number of periods we have per second. //! Note that we want BOARD_CONFIG_BACKLIGHT.timer.peripheral to have as short a period as //! possible for power reasons. static const uint32_t PWM_OUTPUT_FREQUENCY_HZ = 256; static bool s_initialized = false; static bool s_backlight_pwm_enabled = false; //! Bitmask of who wants to hold the LED enable on. //! see \ref led_enable, \ref led_disable, \ref LEDEnabler static uint32_t s_led_enable; static void prv_backlight_pwm_enable(bool on) { pwm_enable(&BOARD_CONFIG_BACKLIGHT.pwm, on); if (on != s_backlight_pwm_enabled) { if (on) { stop_mode_disable(InhibitorBacklight); } else { stop_mode_enable(InhibitorBacklight); } } s_backlight_pwm_enabled = on; } void backlight_init(void) { if (s_initialized) { return; } s_led_enable = 0; if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Ctl) { periph_config_acquire_lock(); gpio_output_init(&BOARD_CONFIG_BACKLIGHT.ctl, GPIO_OType_PP, GPIO_Speed_2MHz); gpio_output_set(&BOARD_CONFIG_BACKLIGHT.ctl, false); periph_config_release_lock(); s_initialized = true; } if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Pwm) { periph_config_acquire_lock(); pwm_init(&BOARD_CONFIG_BACKLIGHT.pwm, TIMER_PERIOD_RESOLUTION, TIMER_PERIOD_RESOLUTION * PWM_OUTPUT_FREQUENCY_HZ); periph_config_release_lock(); s_initialized = true; } if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_IssiI2C) { led_controller_init(); s_initialized = true; } } // TODO: PBL-36077 Move to a generic 4v5 enable void led_enable(LEDEnabler enabler) { if (s_led_enable == 0) { gpio_output_set(&BOARD_CONFIG_BACKLIGHT.ctl, true); } s_led_enable |= enabler; } // TODO: PBL-36077 Move to a generic 4v5 disable void led_disable(LEDEnabler enabler) { s_led_enable &= ~enabler; if (s_led_enable == 0) { gpio_output_set(&BOARD_CONFIG_BACKLIGHT.ctl, false); } } void backlight_set_brightness(uint16_t brightness) { if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Ctl) { if (brightness == 0) { led_disable(LEDEnablerBacklight); } else { led_enable(LEDEnablerBacklight); } } if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Pwm) { if (brightness == 0) { if (s_backlight_pwm_enabled) { prv_backlight_pwm_enable(false); } PWR_TRACK_BACKLIGHT("OFF", PWM_OUTPUT_FREQUENCY_HZ, 0); } else
} if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_IssiI2C) { led_controller_backlight_set_brightness(brightness >> 8); } } void command_backlight_ctl(const char *arg) { const int bright_percent = atoi(arg); if (bright_percent < 0 || bright_percent > 100) { prompt_send_response("Invalid Brightness"); return; } backlight_set_brightness((BACKLIGHT_BRIGHTNESS_MAX * bright_percent) / 100); prompt_send_response("OK"); }
{ if (!s_backlight_pwm_enabled) { prv_backlight_pwm_enable(true); } // By setting higher values in the TIM_Pulse register, we're causing the output waveform // to be low for a longer period of time, which causes the backlight to be brighter. // // The brightness value has a range of 0 to 0x3fff which is 2^15. The period of the timer // counter is 2^10. We want to rescale the brightness range into a subset of the timer // counter range. Different boards will have a different duty cycle that represent the // "fully on" state. const uint32_t pwm_scaling_factor = BACKLIGHT_BRIGHTNESS_MAX / TIMER_PERIOD_RESOLUTION; const uint32_t desired_duty_cycle = brightness * BOARD_CONFIG.backlight_max_duty_cycle_percent / pwm_scaling_factor / 100; pwm_set_duty_cycle(&BOARD_CONFIG_BACKLIGHT.pwm, desired_duty_cycle); PWR_TRACK_BACKLIGHT("ON", PWM_OUTPUT_FREQUENCY_HZ, (desired_duty_cycle * 100) / TIMER_PERIOD_RESOLUTION); }
<|repo_name|>pebble <|file_sep|>src/fw/drivers/backlight.c <|fim_prefix|> | | | | | | | | // | | | | | | | | // ------- ------- ------- -------- // // The resulting waveform has a frequency of PWM_OUTPUT_FREQUENCY_HZ. Inside each period, the timer // counts up to TIMER_PERIOD_RESOLUTION. This means the counter increments at a rate of // PWM_OUTPUT_FREQUENCY_HZ * TIMER_PERIOD_RESOLUTION, which is the frequency that our timer // prescalar has to calculate. The duty cycle is defined by the TIM_Pulse parameter, which // controls after which counter value the output waveform will become active. For example, a // TIM_Pulse value of TIMER_PERIOD_RESOLUTION / 4 will result in an output waveform that will go // active after 25% of it's period has elapsed. //! The counter reload value. The timer will count from 0 to this value and then reset again. //! The TIM_Pulse member below controls for how many of these counts the resulting PWM signal is //! active for. static const uint32_t TIMER_PERIOD_RESOLUTION = 1024; //! The number of periods we have per second. //! Note that we want BOARD_CONFIG_BACKLIGHT.timer.peripheral to have as short a period as //! possible for power reasons. static const uint32_t PWM_OUTPUT_FREQUENCY_HZ = 256; static bool s_initialized = false; static bool s_backlight_pwm_enabled = false; //! Bitmask of who wants to hold the LED enable on. //! see \ref led_enable, \ref led_disable, \ref LEDEnabler static uint32_t s_led_enable; static void prv_backlight_pwm_enable(bool on) { pwm_enable(&BOARD_CONFIG_BACKLIGHT.pwm, on); if (on != s_backlight_pwm_enabled) { if (on) { stop_mode_disable(InhibitorBacklight); } else { stop_mode_enable(InhibitorBacklight); } } s_backlight_pwm_enabled = on; } void backlight_init(void) { if (s_initialized) { return; } s_led_enable = 0; if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Ctl) { periph_config_acquire_lock(); gpio_output_init(&BOARD_CONFIG_BACKLIGHT.ctl, GPIO_OType_PP, GPIO_Speed_2MHz); gpio_output_set(&BOARD_CONFIG_BACKLIGHT.ctl, false); periph_config_release_lock(); s_initialized = true; } if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Pwm) { periph_config_acquire_lock(); pwm_init(&BOARD_CONFIG_BACKLIGHT.pwm, TIMER_PERIOD_RESOLUTION, TIMER_PERIOD_RESOLUTION * PWM_OUTPUT_FREQUENCY_HZ); periph_config_release_lock(); s_initialized = true; } if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_IssiI2C) { led_controller_init(); s_initialized = true; } } // TODO: PBL-36077 Move to a generic 4v5 enable void led_enable(LEDEnabler enabler) { if (s_led_enable == 0) { gpio_output_set(&BOARD_CONFIG_BACKLIGHT.ctl, true); } s_led_enable |= enabler; } // TODO: PBL-36077 Move to a generic 4v5 disable void led_disable(LEDEnabler enabler) { s_led_enable &= ~enabler; if (s_led_enable == 0) { gpio_output_set(&BOARD_CONFIG_BACKLIGHT.ctl, false); } } void backlight_set_brightness(uint16_t brightness) { if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Ctl) { if (brightness == 0) { led_disable(LEDEnablerBacklight); } else { led_enable(LEDEnablerBacklight); } } if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_Pwm) { if (brightness == 0) { if (s_backlight_pwm_enabled) { prv_backlight_pwm_enable(false); } PWR_TRACK_BACKLIGHT("OFF", PWM_OUTPUT_FREQUENCY_HZ, 0); } else <|fim_suffix|> } if (BOARD_CONFIG_BACKLIGHT.options & ActuatorOptions_IssiI2C) { led_controller_backlight_set_brightness(brightness >> 8); } } void command_backlight_ctl(const char *arg) { const int bright_percent = atoi(arg); if (bright_percent < 0 || bright_percent > 100) { prompt_send_response("Invalid Brightness"); return; } backlight_set_brightness((BACKLIGHT_BRIGHTNESS_MAX * bright_percent) / 100); prompt_send_response("OK"); } <|fim_middle|>{ if (!s_backlight_pwm_enabled) { prv_backlight_pwm_enable(true); } // By setting higher values in the TIM_Pulse register, we're causing the output waveform // to be low for a longer period of time, which causes the backlight to be brighter. // // The brightness value has a range of 0 to 0x3fff which is 2^15. The period of the timer // counter is 2^10. We want to rescale the brightness range into a subset of the timer // counter range. Different boards will have a different duty cycle that represent the // "fully on" state. const uint32_t pwm_scaling_factor = BACKLIGHT_BRIGHTNESS_MAX / TIMER_PERIOD_RESOLUTION; const uint32_t desired_duty_cycle = brightness * BOARD_CONFIG.backlight_max_duty_cycle_percent / pwm_scaling_factor / 100; pwm_set_duty_cycle(&BOARD_CONFIG_BACKLIGHT.pwm, desired_duty_cycle); PWR_TRACK_BACKLIGHT("ON", PWM_OUTPUT_FREQUENCY_HZ, (desired_duty_cycle * 100) / TIMER_PERIOD_RESOLUTION); }<|endoftext|>
masked_node
compound_statement
tests/fw/ui/test_text_layer.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "clar.h" #include "applib/ui/text_layer.h" // Stubs ///////////////////// #include "stubs_app_state.h" #include "stubs_graphics.h" #include "stubs_heap.h" #include "stubs_logging.h" #include "stubs_passert.h" #include "stubs_pbl_malloc.h" #include "stubs_pebble_tasks.h" #include "stubs_process_manager.h" #include "stubs_system_theme.h" #include "stubs_ui_window.h" #include "stubs_unobstructed_area.h" GFont fonts_get_system_font(const char *font_key)
void graphics_context_set_fill_color(GContext* ctx, GColor color){} void graphics_context_set_text_color(GContext* ctx, GColor color){} // Fakes //////////////////////// #define MOCKED_CREATED_LAYOUT (GTextLayoutCacheRef)123456 void graphics_text_layout_cache_init(GTextLayoutCacheRef *layout_cache) { *layout_cache = MOCKED_CREATED_LAYOUT; } void graphics_text_layout_cache_deinit(GTextLayoutCacheRef *layout_cache) {} void graphics_text_layout_set_line_spacing_delta(GTextLayoutCacheRef layout, int16_t delta) {} int16_t graphics_text_layout_get_line_spacing_delta(const GTextLayoutCacheRef layout) { return 0; } GSize graphics_text_layout_get_max_used_size(GContext *ctx, const char *text, GFont const font, const GRect box, const GTextOverflowMode overflow_mode, const GTextAlignment alignment, GTextLayoutCacheRef layout) { return GSizeZero; } typedef struct { struct { GTextLayoutCacheRef layout; } disable_text_flow; struct { GTextLayoutCacheRef layout; uint8_t inset; } enable_text_flow; struct { GTextLayoutCacheRef layout; } disable_paging; struct { GTextLayoutCacheRef layout; GPoint origin; GRect paging; } enable_paging; } MockValues; static MockValues s_actual; void graphics_text_attributes_restore_default_text_flow(GTextLayoutCacheRef layout) { s_actual.disable_text_flow.layout = layout; } void graphics_text_attributes_enable_screen_text_flow(GTextLayoutCacheRef layout, uint8_t inset) { s_actual.enable_text_flow.layout = layout; s_actual.enable_text_flow.inset = inset; } void graphics_text_attributes_restore_default_paging(GTextLayoutCacheRef layout) { s_actual.disable_paging.layout = layout; } void graphics_text_attributes_enable_paging(GTextLayoutCacheRef layout, GPoint content_origin_on_screen, GRect paging_on_screen) { s_actual.enable_paging.layout = layout; s_actual.enable_paging.origin = content_origin_on_screen; s_actual.enable_paging.paging = paging_on_screen; } #define MOCKED_PAGING_ORIGIN GPoint(1 ,2) #define MOCKED_PAGING_PAGE GRect(3, 4, 5, 6) bool s_text_layer_calc_text_flow_paging_values_result; bool text_layer_calc_text_flow_paging_values(const TextLayer *text_layer, GPoint *content_origin_on_screen, GRect *page_rect_on_screen) { *content_origin_on_screen = MOCKED_PAGING_ORIGIN; *page_rect_on_screen = MOCKED_PAGING_PAGE; return s_text_layer_calc_text_flow_paging_values_result; } // Tests ////////////////////// #define cl_assert_mocks_called(expected) \ do { \ cl_assert_equal_p((expected).disable_text_flow.layout, s_actual.disable_text_flow.layout); \ cl_assert_equal_p((expected).enable_text_flow.layout, s_actual.enable_text_flow.layout); \ cl_assert_equal_i((expected).enable_text_flow.inset, s_actual.enable_text_flow.inset); \ cl_assert_equal_p((expected).disable_paging.layout, s_actual.disable_paging.layout); \ cl_assert_equal_p((expected).enable_paging.layout, s_actual.enable_paging.layout); \ cl_assert_equal_i((expected).enable_paging.origin.x, s_actual.enable_paging.origin.x); \ cl_assert_equal_i((expected).enable_paging.origin.y, s_actual.enable_paging.origin.y); \ cl_assert_equal_i((expected).enable_paging.paging.origin.x, s_actual.enable_paging.paging.origin.x); \ cl_assert_equal_i((expected).enable_paging.paging.origin.y, s_actual.enable_paging.paging.origin.y); \ cl_assert_equal_i((expected).enable_paging.paging.size.w, s_actual.enable_paging.paging.size.w); \ cl_assert_equal_i((expected).enable_paging.paging.size.h, s_actual.enable_paging.paging.size.h); \ } while(0) Window window; TextLayer text_layer; void test_text_layer__initialize(void) { s_actual = (MockValues){}; window = (Window){}; text_layer_init(&text_layer, &GRect(10, 20, 30, 40)); s_text_layer_calc_
{ return NULL; }
<|repo_name|>pebble <|file_sep|>tests/fw/ui/test_text_layer.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "clar.h" #include "applib/ui/text_layer.h" // Stubs ///////////////////// #include "stubs_app_state.h" #include "stubs_graphics.h" #include "stubs_heap.h" #include "stubs_logging.h" #include "stubs_passert.h" #include "stubs_pbl_malloc.h" #include "stubs_pebble_tasks.h" #include "stubs_process_manager.h" #include "stubs_system_theme.h" #include "stubs_ui_window.h" #include "stubs_unobstructed_area.h" GFont fonts_get_system_font(const char *font_key) <|fim_suffix|> void graphics_context_set_fill_color(GContext* ctx, GColor color){} void graphics_context_set_text_color(GContext* ctx, GColor color){} // Fakes //////////////////////// #define MOCKED_CREATED_LAYOUT (GTextLayoutCacheRef)123456 void graphics_text_layout_cache_init(GTextLayoutCacheRef *layout_cache) { *layout_cache = MOCKED_CREATED_LAYOUT; } void graphics_text_layout_cache_deinit(GTextLayoutCacheRef *layout_cache) {} void graphics_text_layout_set_line_spacing_delta(GTextLayoutCacheRef layout, int16_t delta) {} int16_t graphics_text_layout_get_line_spacing_delta(const GTextLayoutCacheRef layout) { return 0; } GSize graphics_text_layout_get_max_used_size(GContext *ctx, const char *text, GFont const font, const GRect box, const GTextOverflowMode overflow_mode, const GTextAlignment alignment, GTextLayoutCacheRef layout) { return GSizeZero; } typedef struct { struct { GTextLayoutCacheRef layout; } disable_text_flow; struct { GTextLayoutCacheRef layout; uint8_t inset; } enable_text_flow; struct { GTextLayoutCacheRef layout; } disable_paging; struct { GTextLayoutCacheRef layout; GPoint origin; GRect paging; } enable_paging; } MockValues; static MockValues s_actual; void graphics_text_attributes_restore_default_text_flow(GTextLayoutCacheRef layout) { s_actual.disable_text_flow.layout = layout; } void graphics_text_attributes_enable_screen_text_flow(GTextLayoutCacheRef layout, uint8_t inset) { s_actual.enable_text_flow.layout = layout; s_actual.enable_text_flow.inset = inset; } void graphics_text_attributes_restore_default_paging(GTextLayoutCacheRef layout) { s_actual.disable_paging.layout = layout; } void graphics_text_attributes_enable_paging(GTextLayoutCacheRef layout, GPoint content_origin_on_screen, GRect paging_on_screen) { s_actual.enable_paging.layout = layout; s_actual.enable_paging.origin = content_origin_on_screen; s_actual.enable_paging.paging = paging_on_screen; } #define MOCKED_PAGING_ORIGIN GPoint(1 ,2) #define MOCKED_PAGING_PAGE GRect(3, 4, 5, 6) bool s_text_layer_calc_text_flow_paging_values_result; bool text_layer_calc_text_flow_paging_values(const TextLayer *text_layer, GPoint *content_origin_on_screen, GRect *page_rect_on_screen) { *content_origin_on_screen = MOCKED_PAGING_ORIGIN; *page_rect_on_screen = MOCKED_PAGING_PAGE; return s_text_layer_calc_text_flow_paging_values_result; } // Tests ////////////////////// #define cl_assert_mocks_called(expected) \ do { \ cl_assert_equal_p((expected).disable_text_flow.layout, s_actual.disable_text_flow.layout); \ cl_assert_equal_p((expected).enable_text_flow.layout, s_actual.enable_text_flow.layout); \ cl_assert_equal_i((expected).enable_text_flow.inset, s_actual.enable_text_flow.inset); \ cl_assert_equal_p((expected).disable_paging.layout, s_actual.disable_paging.layout); \ cl_assert_equal_p((expected).enable_paging.layout, s_actual.enable_paging.layout); \ cl_assert_equal_i((expected).enable_paging.origin.x, s_actual.enable_paging.origin.x); \ cl_assert_equal_i((expected).enable_paging.origin.y, s_actual.enable_paging.origin.y); \ cl_assert_equal_i((expected).enable_paging.paging.origin.x, s_actual.enable_paging.paging.origin.x); \ cl_assert_equal_i((expected).enable_paging.paging.origin.y, s_actual.enable_paging.paging.origin.y); \ cl_assert_equal_i((expected).enable_paging.paging.size.w, s_actual.enable_paging.paging.size.w); \ cl_assert_equal_i((expected).enable_paging.paging.size.h, s_actual.enable_paging.paging.size.h); \ } while(0) Window window; TextLayer text_layer; void test_text_layer__initialize(void) { s_actual = (MockValues){}; window = (Window){}; text_layer_init(&text_layer, &GRect(10, 20, 30, 40)); s_text_layer_calc_<|fim_middle|>{ return NULL; }<|endoftext|>
masked_node
argument_list
src/fw/applib/ui/dialogs/bt_conn_dialog.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "bt_conn_dialog.h" #include "applib/applib_malloc.auto.h" #include "applib/ui/dialogs/dialog.h" #include "applib/ui/dialogs/dialog_private.h" #include "applib/ui/window.h" #include "kernel/events.h" #include "kernel/pebble_tasks.h" #include "kernel/ui/modals/modal_manager.h" #include "process_state/app_state/app_state.h" #include "resource/resource_ids.auto.h" #include "services/common/i18n/i18n.h" #include "syscall/syscall.h" #include "system/passert.h" static void prv_handle_comm_session_event(PebbleEvent *e, void *context) { BtConnDialog *bt_dialog = context; if (!e->bluetooth.comm_session_event.is_system) { return; } if (e->bluetooth.comm_session_event.is_open) { if (bt_dialog->connected_handler) { bt_dialog->connected_handler(true, bt_dialog->context); } // handler to NULL so it won't be called again during the unload bt_dialog->connected_handler = NULL; dialog_pop(&bt_dialog->dialog.dialog); } } static void prv_bt_dialog_unload(void *context) { BtConnDialog *bt_dialog = context; event_service_client_unsubscribe(&bt_dialog->pebble_app_event_sub); if (bt_dialog->connected_handler) { bt_dialog->connected_handler(false, bt_dialog->context); } if (bt_dialog->owns_buffer) { applib_free(bt_dialog->text_buffer); } } void bt_conn_dialog_push(BtConnDialog *bt_dialog, BtConnDialogResultHandler handler, void *context) { if (!bt_dialog) { bt_dialog = bt_conn_dialog_create(); if (!bt_dialog) { return; } } bt_dialog->connected_handler = handler; bt_dialog->context = context; bt_dialog->pebble_app_event_sub = (EventServiceInfo) { .type = PEBBLE_COMM_SESSION_EVENT, .handler = prv_handle_comm_session_event, .context = bt_dialog }; event_service_client_subscribe(&bt_dialog->pebble_app_event_sub); WindowStack *window_stack = NULL; if (pebble_task_get_current() == PebbleTask_App) { window_stack = app_state_get_window_stack(); } else { // Bluetooth disconnection events are always displayed at maximum priority. window_stack = modal_manager_get_window_stack
; } simple_dialog_push(&bt_dialog->dialog, window_stack); } BtConnDialog *bt_conn_dialog_create(void) { BtConnDialog *bt_dialog = applib_malloc(sizeof(BtConnDialog)); bt_conn_dialog_init(bt_dialog, NULL, 0); return bt_dialog; } void bt_conn_dialog_init(BtConnDialog *bt_dialog, char *text_buffer, size_t buffer_size) { memset(bt_dialog, 0, sizeof(BtConnDialog)); simple_dialog_init(&bt_dialog->dialog, "Bluetooth Disconnected"); Dialog *dialog = &bt_dialog->dialog.dialog; size_t len = sys_i18n_get_length("Check bluetooth connection"); if (text_buffer) { PBL_ASSERTN(len < buffer_size); bt_dialog->text_buffer = text_buffer; bt_dialog->owns_buffer = false; } else { buffer_size = len + 1; bt_dialog->text_buffer = applib_malloc(buffer_size); bt_dialog->owns_buffer = true; } sys_i18n_get_with_buffer("Check bluetooth connection", bt_dialog->text_buffer, buffer_size); dialog_set_text(dialog, bt_dialog->text_buffer); dialog_set_icon(dialog, RESOURCE_ID_WATCH_DISCONNECTED_LARGE); dialog_show_status_bar_layer(dialog, true); dialog_set_callbacks(dialog, &(DialogCallbacks) { .unload = prv_bt_dialog_unload }, bt_dialog); }
(ModalPriorityCritical)
<|repo_name|>pebble <|file_sep|>src/fw/applib/ui/dialogs/bt_conn_dialog.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "bt_conn_dialog.h" #include "applib/applib_malloc.auto.h" #include "applib/ui/dialogs/dialog.h" #include "applib/ui/dialogs/dialog_private.h" #include "applib/ui/window.h" #include "kernel/events.h" #include "kernel/pebble_tasks.h" #include "kernel/ui/modals/modal_manager.h" #include "process_state/app_state/app_state.h" #include "resource/resource_ids.auto.h" #include "services/common/i18n/i18n.h" #include "syscall/syscall.h" #include "system/passert.h" static void prv_handle_comm_session_event(PebbleEvent *e, void *context) { BtConnDialog *bt_dialog = context; if (!e->bluetooth.comm_session_event.is_system) { return; } if (e->bluetooth.comm_session_event.is_open) { if (bt_dialog->connected_handler) { bt_dialog->connected_handler(true, bt_dialog->context); } // handler to NULL so it won't be called again during the unload bt_dialog->connected_handler = NULL; dialog_pop(&bt_dialog->dialog.dialog); } } static void prv_bt_dialog_unload(void *context) { BtConnDialog *bt_dialog = context; event_service_client_unsubscribe(&bt_dialog->pebble_app_event_sub); if (bt_dialog->connected_handler) { bt_dialog->connected_handler(false, bt_dialog->context); } if (bt_dialog->owns_buffer) { applib_free(bt_dialog->text_buffer); } } void bt_conn_dialog_push(BtConnDialog *bt_dialog, BtConnDialogResultHandler handler, void *context) { if (!bt_dialog) { bt_dialog = bt_conn_dialog_create(); if (!bt_dialog) { return; } } bt_dialog->connected_handler = handler; bt_dialog->context = context; bt_dialog->pebble_app_event_sub = (EventServiceInfo) { .type = PEBBLE_COMM_SESSION_EVENT, .handler = prv_handle_comm_session_event, .context = bt_dialog }; event_service_client_subscribe(&bt_dialog->pebble_app_event_sub); WindowStack *window_stack = NULL; if (pebble_task_get_current() == PebbleTask_App) { window_stack = app_state_get_window_stack(); } else { // Bluetooth disconnection events are always displayed at maximum priority. window_stack = modal_manager_get_window_stack<|fim_suffix|>; } simple_dialog_push(&bt_dialog->dialog, window_stack); } BtConnDialog *bt_conn_dialog_create(void) { BtConnDialog *bt_dialog = applib_malloc(sizeof(BtConnDialog)); bt_conn_dialog_init(bt_dialog, NULL, 0); return bt_dialog; } void bt_conn_dialog_init(BtConnDialog *bt_dialog, char *text_buffer, size_t buffer_size) { memset(bt_dialog, 0, sizeof(BtConnDialog)); simple_dialog_init(&bt_dialog->dialog, "Bluetooth Disconnected"); Dialog *dialog = &bt_dialog->dialog.dialog; size_t len = sys_i18n_get_length("Check bluetooth connection"); if (text_buffer) { PBL_ASSERTN(len < buffer_size); bt_dialog->text_buffer = text_buffer; bt_dialog->owns_buffer = false; } else { buffer_size = len + 1; bt_dialog->text_buffer = applib_malloc(buffer_size); bt_dialog->owns_buffer = true; } sys_i18n_get_with_buffer("Check bluetooth connection", bt_dialog->text_buffer, buffer_size); dialog_set_text(dialog, bt_dialog->text_buffer); dialog_set_icon(dialog, RESOURCE_ID_WATCH_DISCONNECTED_LARGE); dialog_show_status_bar_layer(dialog, true); dialog_set_callbacks(dialog, &(DialogCallbacks) { .unload = prv_bt_dialog_unload }, bt_dialog); } <|fim_middle|>(ModalPriorityCritical)<|endoftext|>
masked_node
compound_statement
src/fw/apps/system_apps/alarms/alarm_editor.c
//////////////////////////////////////////////////////////////////////////////// //! Day Picker static void prv_day_picker_window_unload(Window *window) { AlarmEditorData *data = (AlarmEditorData*) window_get_user_data(window); if (!data->day_picker_was_completed && data->time_picker_was_completed) { // If we cancel the day picker go back to the time picker data->time_picker_was_completed = false; return; } if (data->creating_alarm) { time_selection_window_deinit(&data->time_picker_window); } // Editing recurrence menu_layer_deinit(&data->day_picker_menu_layer); prv_remove_windows(data); i18n_free_all(&data->day_picker_window); task_free(data); data = NULL; } static void prv_handle_selection(int index, void *callback_context) { AlarmEditorData *data = (AlarmEditorData *)callback_context; data->day_picker_was_completed = true; data->alarm_kind = prv_index_to_alarm_kind(index); if (data->creating_alarm) { const AlarmInfo info = { .hour = data->alarm_hour, .minute = data->alarm_minute, .kind = data->alarm_kind, .is_smart = (data->alarm_type == AlarmType_Smart), }; data->alarm_id = alarm_create(&info); data->complete_callback(CREATED, data->alarm_id, data->callback_context); app_window_stack_remove(&data->day_picker_window, true); } else { alarm_set_kind(data->alarm_id, data->alarm_kind); data->complete_callback(EDITED, data->alarm_id, data->callback_context); app_window_stack_pop(true); } } /////////////////////////////////////////////////////////////////////////////////////////////////// //! Custom Day Picker static void prv_custom_day_picker_window_unload(Window *window) { AlarmEditorData *data = (AlarmEditorData*) window_get_user_data(window); if (!data->custom_day_picker_was_completed) { // If we cancel the custom day picker go back to the day picker data->day_picker_was_completed = false; i18n_free_all(&data->custom_day_picker_window); return; } menu_layer_deinit(&data->custom_day_picker_menu_layer); prv_remove_windows(data); i18n_free_all(&data->custom_day_picker_window); } static void prv_handle_custom_day_selection(int index, void *callback_context) { AlarmEditorData *data = (AlarmEditorData *)callback_context; prv_setup_custom_day_picker_window(data); } /////////////////////////////////////////////////////////////////////////////////////////////////// //! Menu Layer Callbacks static uint16_t prv_day_picker_get_num_sections(struct MenuLayer *menu_layer, void *callback_context) { return 1; } static uint16_t prv_day_picker_get_num_rows(struct MenuLayer *menu_layer, uint16_t section_index, void *callback_context) { return DayPickerMenuItemsNumItems; } static int16_t prv_day_picker_get_cell_height(struct MenuLayer *menu_layer, MenuIndex *cell_index, void *callback_context) { return ALARM_DAY_LIST_CELL_HEIGHT; } static void prv_day_picker_draw_row(GContext *ctx, const Layer *cell_layer, MenuIndex *cell_index, void *callback_context) { AlarmEditorData *data = (AlarmEditorData *)callback_context; AlarmKind kind = prv_index_to_alarm_kind(cell_index->row); const bool all_caps = false; const char *cell_text = alarm_get_string_for_kind(kind, all_caps); menu_cell_basic_draw(ctx, cell_layer, i18n_get(cell_text, &data->day_picker_window), NULL, NULL); } static void prv_day_picker_handle_selection(MenuLayer *menu_layer, MenuIndex *cell_index, void *callback_context) { AlarmEditorData *data = (AlarmEditorData *)callback_context; data->day_picker_was_completed = false; if (cell_index->row == DayPickerMenuItemsCustom) { prv_handle_custom_day_selection(cell_index->row, callback_context); } else
} static void prv_setup_day_picker_window(AlarmEditorData *data) { window_init(&data->day_picker_window, WINDOW_NAME("Alarm Day Picker")); window_set_user_data(&data->day_picker_window, data); data->day_picker_window.window_handlers.unload = prv_day_picker_window_unload; GRect bounds = data->day_picker_window.layer.bounds; #if PBL_ROUND bounds = grect_inset_internal(bounds, 0, STATUS_BAR_LAYER_HEIGHT); #endif menu_layer_init(&data->day_picker_menu_layer, &bounds); menu_layer_set_callbacks(&data->day_picker_menu_layer, data, &(MenuLayerCallbacks) { .get_num_sections = prv_day_picker_get_num_sections, .get_num_rows = prv_day_picker_get_num_rows, .get_cell_height = prv_day_picker_get_cell_height, .draw_row = prv_day_picker_draw_row, .select_click = prv_day_picker_handle_selection, }); menu_layer_set_highlight_colors(&data->day_picker_menu_layer, ALARMS_APP_HIGHLIGHT_COLOR, GColorWhite); menu_layer_set_click_config_onto_window(&data->day_picker_menu_layer, &data->day_picker_window); layer_add_child(&data->day_picker_window.layer, menu_layer_get_layer(&data->day_picker_menu_layer)); if (!alarm_get_kind(data->alarm_id, &data->alarm_kind)) { data->alarm_kind = ALARM_KIND_JUST_ONCE; } menu_layer_set_selected_index(&data->day_picker_menu_layer, (MenuIndex) { 0, prv_alarm_kind_to_index(data->alarm_kind) }, MenuRowAlignCenter, false); } static uint16_t prv_custom_day_picker_get_num_sections(struct MenuLayer *menu_layer, void *callback_context) { return 1; } static uint16_t prv_custom_day_picker_get_num_rows(struct MenuLayer *menu_layer, uint16_t section_index, void *callback_context) { return DAYS_PER_WEEK + 1; } static int16_t prv_custom_day_picker_get_cell_height(struct MenuLayer *menu_layer, MenuIndex *cell_index, void *callback_context) { return ALARM_DAY_LIST_CELL_HEIGHT; } static void prv_custom_day_picker_draw_row(GContext *ctx, const Layer *cell_layer, MenuIndex *cell_index, void *callback_context) { AlarmEditorData *data = (AlarmEditorData *)callback_context; GBitmap *ptr_bitmap; if (cell_index->row == 0) { // "completed selection" row GRect box; uint32_t new_resource_id = RESOURCE_ID_CHECKMARK_ICON_BLACK; if (!prv_is_custom_day_scheduled(data)) { // no days selected if (menu_cell_layer_is_highlighted(cell_layer)) { if (data->show_check_something_first_text) { // clicking "complete" when no days selected box.size = GSize(cell_layer->bounds.size.w, ALARM_DAY_LIST_CELL_HEIGHT); box.origin = GPoint(0, 4); graphics_draw_text(ctx, i18n_get("Check something first.", &data->custom_day_picker_window), fonts_get_system_font(FONT_KEY_GOTHIC_18), box, GTextOverflowModeFill, GTextAlignmentCenter, NULL); return; } else { // row highlighted and no days selected new_resource_id = RESOURCE_ID_CHECKMARK_ICON_DOTTED; } } } if (new_resource_id != data->current_checkmark_icon_resource_id) { data->current_checkmark_icon_resource_id = new_resource_id; gbitmap_deinit(&data->checkmark_icon); gbitmap_init_with_resource(&data->checkmark_icon, data->current_checkmark_icon_resource_id); } box.origin = GPoint((((cell_layer->bounds.size.w)/2)-((data->checkmark_icon.bounds.size.w)/2)), (((cell_layer->bounds.size.h)/2)-((data->checkmark_icon.bounds.size.h)/2))); box.size = data->checkmark_icon.bounds.size; graphics_context_set_compositing_mode(ctx, GCompOpTint);
{ data->day_picker_was_completed = true; prv_handle_selection(cell_index->row, callback_context); }
<|repo_name|>pebble <|file_sep|>src/fw/apps/system_apps/alarms/alarm_editor.c <|fim_prefix|>//////////////////////////////////////////////////////////////////////////////// //! Day Picker static void prv_day_picker_window_unload(Window *window) { AlarmEditorData *data = (AlarmEditorData*) window_get_user_data(window); if (!data->day_picker_was_completed && data->time_picker_was_completed) { // If we cancel the day picker go back to the time picker data->time_picker_was_completed = false; return; } if (data->creating_alarm) { time_selection_window_deinit(&data->time_picker_window); } // Editing recurrence menu_layer_deinit(&data->day_picker_menu_layer); prv_remove_windows(data); i18n_free_all(&data->day_picker_window); task_free(data); data = NULL; } static void prv_handle_selection(int index, void *callback_context) { AlarmEditorData *data = (AlarmEditorData *)callback_context; data->day_picker_was_completed = true; data->alarm_kind = prv_index_to_alarm_kind(index); if (data->creating_alarm) { const AlarmInfo info = { .hour = data->alarm_hour, .minute = data->alarm_minute, .kind = data->alarm_kind, .is_smart = (data->alarm_type == AlarmType_Smart), }; data->alarm_id = alarm_create(&info); data->complete_callback(CREATED, data->alarm_id, data->callback_context); app_window_stack_remove(&data->day_picker_window, true); } else { alarm_set_kind(data->alarm_id, data->alarm_kind); data->complete_callback(EDITED, data->alarm_id, data->callback_context); app_window_stack_pop(true); } } /////////////////////////////////////////////////////////////////////////////////////////////////// //! Custom Day Picker static void prv_custom_day_picker_window_unload(Window *window) { AlarmEditorData *data = (AlarmEditorData*) window_get_user_data(window); if (!data->custom_day_picker_was_completed) { // If we cancel the custom day picker go back to the day picker data->day_picker_was_completed = false; i18n_free_all(&data->custom_day_picker_window); return; } menu_layer_deinit(&data->custom_day_picker_menu_layer); prv_remove_windows(data); i18n_free_all(&data->custom_day_picker_window); } static void prv_handle_custom_day_selection(int index, void *callback_context) { AlarmEditorData *data = (AlarmEditorData *)callback_context; prv_setup_custom_day_picker_window(data); } /////////////////////////////////////////////////////////////////////////////////////////////////// //! Menu Layer Callbacks static uint16_t prv_day_picker_get_num_sections(struct MenuLayer *menu_layer, void *callback_context) { return 1; } static uint16_t prv_day_picker_get_num_rows(struct MenuLayer *menu_layer, uint16_t section_index, void *callback_context) { return DayPickerMenuItemsNumItems; } static int16_t prv_day_picker_get_cell_height(struct MenuLayer *menu_layer, MenuIndex *cell_index, void *callback_context) { return ALARM_DAY_LIST_CELL_HEIGHT; } static void prv_day_picker_draw_row(GContext *ctx, const Layer *cell_layer, MenuIndex *cell_index, void *callback_context) { AlarmEditorData *data = (AlarmEditorData *)callback_context; AlarmKind kind = prv_index_to_alarm_kind(cell_index->row); const bool all_caps = false; const char *cell_text = alarm_get_string_for_kind(kind, all_caps); menu_cell_basic_draw(ctx, cell_layer, i18n_get(cell_text, &data->day_picker_window), NULL, NULL); } static void prv_day_picker_handle_selection(MenuLayer *menu_layer, MenuIndex *cell_index, void *callback_context) { AlarmEditorData *data = (AlarmEditorData *)callback_context; data->day_picker_was_completed = false; if (cell_index->row == DayPickerMenuItemsCustom) { prv_handle_custom_day_selection(cell_index->row, callback_context); } else <|fim_suffix|> } static void prv_setup_day_picker_window(AlarmEditorData *data) { window_init(&data->day_picker_window, WINDOW_NAME("Alarm Day Picker")); window_set_user_data(&data->day_picker_window, data); data->day_picker_window.window_handlers.unload = prv_day_picker_window_unload; GRect bounds = data->day_picker_window.layer.bounds; #if PBL_ROUND bounds = grect_inset_internal(bounds, 0, STATUS_BAR_LAYER_HEIGHT); #endif menu_layer_init(&data->day_picker_menu_layer, &bounds); menu_layer_set_callbacks(&data->day_picker_menu_layer, data, &(MenuLayerCallbacks) { .get_num_sections = prv_day_picker_get_num_sections, .get_num_rows = prv_day_picker_get_num_rows, .get_cell_height = prv_day_picker_get_cell_height, .draw_row = prv_day_picker_draw_row, .select_click = prv_day_picker_handle_selection, }); menu_layer_set_highlight_colors(&data->day_picker_menu_layer, ALARMS_APP_HIGHLIGHT_COLOR, GColorWhite); menu_layer_set_click_config_onto_window(&data->day_picker_menu_layer, &data->day_picker_window); layer_add_child(&data->day_picker_window.layer, menu_layer_get_layer(&data->day_picker_menu_layer)); if (!alarm_get_kind(data->alarm_id, &data->alarm_kind)) { data->alarm_kind = ALARM_KIND_JUST_ONCE; } menu_layer_set_selected_index(&data->day_picker_menu_layer, (MenuIndex) { 0, prv_alarm_kind_to_index(data->alarm_kind) }, MenuRowAlignCenter, false); } static uint16_t prv_custom_day_picker_get_num_sections(struct MenuLayer *menu_layer, void *callback_context) { return 1; } static uint16_t prv_custom_day_picker_get_num_rows(struct MenuLayer *menu_layer, uint16_t section_index, void *callback_context) { return DAYS_PER_WEEK + 1; } static int16_t prv_custom_day_picker_get_cell_height(struct MenuLayer *menu_layer, MenuIndex *cell_index, void *callback_context) { return ALARM_DAY_LIST_CELL_HEIGHT; } static void prv_custom_day_picker_draw_row(GContext *ctx, const Layer *cell_layer, MenuIndex *cell_index, void *callback_context) { AlarmEditorData *data = (AlarmEditorData *)callback_context; GBitmap *ptr_bitmap; if (cell_index->row == 0) { // "completed selection" row GRect box; uint32_t new_resource_id = RESOURCE_ID_CHECKMARK_ICON_BLACK; if (!prv_is_custom_day_scheduled(data)) { // no days selected if (menu_cell_layer_is_highlighted(cell_layer)) { if (data->show_check_something_first_text) { // clicking "complete" when no days selected box.size = GSize(cell_layer->bounds.size.w, ALARM_DAY_LIST_CELL_HEIGHT); box.origin = GPoint(0, 4); graphics_draw_text(ctx, i18n_get("Check something first.", &data->custom_day_picker_window), fonts_get_system_font(FONT_KEY_GOTHIC_18), box, GTextOverflowModeFill, GTextAlignmentCenter, NULL); return; } else { // row highlighted and no days selected new_resource_id = RESOURCE_ID_CHECKMARK_ICON_DOTTED; } } } if (new_resource_id != data->current_checkmark_icon_resource_id) { data->current_checkmark_icon_resource_id = new_resource_id; gbitmap_deinit(&data->checkmark_icon); gbitmap_init_with_resource(&data->checkmark_icon, data->current_checkmark_icon_resource_id); } box.origin = GPoint((((cell_layer->bounds.size.w)/2)-((data->checkmark_icon.bounds.size.w)/2)), (((cell_layer->bounds.size.h)/2)-((data->checkmark_icon.bounds.size.h)/2))); box.size = data->checkmark_icon.bounds.size; graphics_context_set_compositing_mode(ctx, GCompOpTint); <|fim_middle|>{ data->day_picker_was_completed = true; prv_handle_selection(cell_index->row, callback_context); }<|endoftext|>
masked_node
compound_statement
src/fw/services/normal/send_text_service.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "send_text_service.h" #include "applib/event_service_client.h" #include "kernel/events.h" #include "services/common/bluetooth/bluetooth_persistent_storage.h" #include "services/normal/blob_db/ios_notif_pref_db.h" #include "services/normal/notifications/notification_constants.h" static bool s_has_send_text_reply_action = false; static bool prv_has_send_text_reply_action(void) { iOSNotifPrefs *notif_prefs = ios_notif_pref_db_get_prefs((uint8_t *)SEND_TEXT_NOTIF_PREF_KEY, strlen(SEND_TEXT_NOTIF_PREF_KEY)); if (!notif_prefs) { return false; } bool has_reply_action = (timeline_item_action_group_find_reply_action(&notif_prefs->action_group) != NULL); ios_notif_pref_db_free_prefs(notif_prefs); return has_reply_action; } static void prv_blobdb_event_handler(PebbleEvent *event, void *context) { const PebbleBlobDBEvent *blobdb_event = &event->blob_db; if (blobdb_event->db_id != BlobDBIdiOSNotifPref) { return; } if (blobdb_event->type != BlobDBEventTypeFlush && memcmp(blobdb_event->key, (uint8_t *)SEND_TEXT_NOTIF_PREF_KEY, strlen(SEND_TEXT_NOTIF_PREF_KEY)))
s_has_send_text_reply_action = prv_has_send_text_reply_action(); } void send_text_service_init(void) { // Save the initial state s_has_send_text_reply_action = prv_has_send_text_reply_action();; // Register for updates static EventServiceInfo s_blobdb_event_info = { .type = PEBBLE_BLOBDB_EVENT, .handler = prv_blobdb_event_handler, }; event_service_client_subscribe(&s_blobdb_event_info); } bool send_text_service_is_send_text_supported(void) { PebbleProtocolCapabilities capabilities; bt_persistent_storage_get_cached_system_capabilities(&capabilities); return (capabilities.send_text_support && s_has_send_text_reply_action); }
{ return; }
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/send_text_service.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "send_text_service.h" #include "applib/event_service_client.h" #include "kernel/events.h" #include "services/common/bluetooth/bluetooth_persistent_storage.h" #include "services/normal/blob_db/ios_notif_pref_db.h" #include "services/normal/notifications/notification_constants.h" static bool s_has_send_text_reply_action = false; static bool prv_has_send_text_reply_action(void) { iOSNotifPrefs *notif_prefs = ios_notif_pref_db_get_prefs((uint8_t *)SEND_TEXT_NOTIF_PREF_KEY, strlen(SEND_TEXT_NOTIF_PREF_KEY)); if (!notif_prefs) { return false; } bool has_reply_action = (timeline_item_action_group_find_reply_action(&notif_prefs->action_group) != NULL); ios_notif_pref_db_free_prefs(notif_prefs); return has_reply_action; } static void prv_blobdb_event_handler(PebbleEvent *event, void *context) { const PebbleBlobDBEvent *blobdb_event = &event->blob_db; if (blobdb_event->db_id != BlobDBIdiOSNotifPref) { return; } if (blobdb_event->type != BlobDBEventTypeFlush && memcmp(blobdb_event->key, (uint8_t *)SEND_TEXT_NOTIF_PREF_KEY, strlen(SEND_TEXT_NOTIF_PREF_KEY))) <|fim_suffix|> s_has_send_text_reply_action = prv_has_send_text_reply_action(); } void send_text_service_init(void) { // Save the initial state s_has_send_text_reply_action = prv_has_send_text_reply_action();; // Register for updates static EventServiceInfo s_blobdb_event_info = { .type = PEBBLE_BLOBDB_EVENT, .handler = prv_blobdb_event_handler, }; event_service_client_subscribe(&s_blobdb_event_info); } bool send_text_service_is_send_text_supported(void) { PebbleProtocolCapabilities capabilities; bt_persistent_storage_get_cached_system_capabilities(&capabilities); return (capabilities.send_text_support && s_has_send_text_reply_action); } <|fim_middle|>{ return; }<|endoftext|>
masked_node
call_expression
src/fw/apps/demo_apps/flash_prof.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "process_management/pebble_process_md.h" #include "applib/app.h" #include "system/logging.h" #include "drivers/flash.h" #include "drivers/rtc.h" #include "flash_region/flash_region.h" #include "system/passert.h" #include "kernel/pbl_malloc.h" #include "applib/ui/app_window_stack.h" #include "applib/ui/number_window.h" #include "applib/ui/window_stack.h" #include "FreeRTOS.h" static NumberWindow number_window; static uint32_t timed_read_bytes(uint32_t num_bytes) { uint8_t *buffer = kernel_malloc_check(num_bytes); time_t start_time_s; uint16_t start_time_ms; rtc_get_time_ms(&start_time_s, &start_time_ms); flash_read_bytes(buffer, FLASH_REGION_FILESYSTEM_BEGIN, num_bytes); time_t stop_time_s; uint16_t stop_time_ms; rtc_get_time_ms(&stop_time_s, &stop_time_ms); kernel_free(buffer); return ((stop_time_s * 1000 + stop_time_ms) - (start_time_s * 1000 + start_time_ms)); } static void do_timed_read(NumberWindow *nw, void *data) { uint32_t num_bytes = nw->value; uint32_t predicted_time = num_bytes * 8 / 16000; uint32_t time = timed_read_bytes(num_bytes); PBL_LOG(LOG_LEVEL_DEBUG, "time to read %lu bytes: predicted %lu, actual %lu", num_bytes, predicted_time, time); window_stack_remove(&number_window.window, false); app_window_stack_push(&number_window.window, true); } #define NUM_BYTES 1000 static void handle_init(void) { number_window_init(&number_window, "Num Writes", (NumberWindowCallbacks) { .selected = (NumberWindowCallback) do_timed_read, }, NULL); number_window_set_min(&number_window, 1000); number_window_set_max(&number_window, 1000000); number_window_set_step_size(&number_window, 1000);
; } static void handle_deinit(void) { } static void s_main(void) { handle_init(); app_event_loop(); handle_deinit(); } const PebbleProcessMd* flash_prof_get_app_info() { static const PebbleProcessMdSystem s_app_info = { .common.main_func = &s_main, .name = "Flash Prof" }; return (const PebbleProcessMd*) &s_app_info; }
app_window_stack_push((Window *)&number_window, true)
<|repo_name|>pebble <|file_sep|>src/fw/apps/demo_apps/flash_prof.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "process_management/pebble_process_md.h" #include "applib/app.h" #include "system/logging.h" #include "drivers/flash.h" #include "drivers/rtc.h" #include "flash_region/flash_region.h" #include "system/passert.h" #include "kernel/pbl_malloc.h" #include "applib/ui/app_window_stack.h" #include "applib/ui/number_window.h" #include "applib/ui/window_stack.h" #include "FreeRTOS.h" static NumberWindow number_window; static uint32_t timed_read_bytes(uint32_t num_bytes) { uint8_t *buffer = kernel_malloc_check(num_bytes); time_t start_time_s; uint16_t start_time_ms; rtc_get_time_ms(&start_time_s, &start_time_ms); flash_read_bytes(buffer, FLASH_REGION_FILESYSTEM_BEGIN, num_bytes); time_t stop_time_s; uint16_t stop_time_ms; rtc_get_time_ms(&stop_time_s, &stop_time_ms); kernel_free(buffer); return ((stop_time_s * 1000 + stop_time_ms) - (start_time_s * 1000 + start_time_ms)); } static void do_timed_read(NumberWindow *nw, void *data) { uint32_t num_bytes = nw->value; uint32_t predicted_time = num_bytes * 8 / 16000; uint32_t time = timed_read_bytes(num_bytes); PBL_LOG(LOG_LEVEL_DEBUG, "time to read %lu bytes: predicted %lu, actual %lu", num_bytes, predicted_time, time); window_stack_remove(&number_window.window, false); app_window_stack_push(&number_window.window, true); } #define NUM_BYTES 1000 static void handle_init(void) { number_window_init(&number_window, "Num Writes", (NumberWindowCallbacks) { .selected = (NumberWindowCallback) do_timed_read, }, NULL); number_window_set_min(&number_window, 1000); number_window_set_max(&number_window, 1000000); number_window_set_step_size(&number_window, 1000); <|fim_suffix|>; } static void handle_deinit(void) { } static void s_main(void) { handle_init(); app_event_loop(); handle_deinit(); } const PebbleProcessMd* flash_prof_get_app_info() { static const PebbleProcessMdSystem s_app_info = { .common.main_func = &s_main, .name = "Flash Prof" }; return (const PebbleProcessMd*) &s_app_info; } <|fim_middle|>app_window_stack_push((Window *)&number_window, true)<|endoftext|>
prefix_only
call_expression
src/fw/applib/graphics/gdraw_command.c
"AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "applib/applib_resource_private.h" #include "gdraw_command.h" #include "gdraw_command_private.h" #include "applib/applib_malloc.auto.h" #include "applib/graphics/gpath.h" #include "system/passert.h" #include "syscall/syscall.h" #include "util/net.h" bool gdraw_command_resource_is_valid(ResAppNum app_num, uint32_t resource_id, uint32_t expected_signature, uint32_t *data_size) { // Load file signature, and check that it matches the expected_signature uint32_t data_signature; if (!(sys_resource_load_range(app_num, resource_id, 0, (uint8_t*)&data_signature, sizeof(data_signature)) == sizeof(data_signature) && (ntohl(data_signature) == expected_signature))) { return NULL; } // Data is the second entry after the resource signature if (data_size) { uint32_t output_data_size; _Static_assert(PDCI_SIZE_OFFSET == PDCS_SIZE_OFFSET, "code re-use between PDCI/PDCS requires same file format header"); if (sys_resource_load_range(app_num, resource_id, sizeof(expected_signature), (uint8_t*)&output_data_size, sizeof(output_data_size)) != sizeof(output_data_size)) { return NULL; } *data_size = output_data_size; } return true; } bool gdraw_command_validate(GDrawCommand *command, size_t size) { if ((size < gdraw_command_get_data_size(command))) { return false; } return (((command->type == GDrawCommandTypeCircle) && (command->num_points == 1)) || ((command->type == GDrawCommandTypePath) && (command->num_points > 1)) || ((command->type == GDrawCommandTypePrecisePath) && (command->num_points > 1))); } static void prv_draw_path(GContext *ctx, GDrawCommand *command) { if (command->num_points <= 1) { return; } GPath path = { .num_points = command->num_points, .points = command->points }; // draw all values of alpha, except fully transparent if ((command->fill_color.a != 0)) { graphics_context_set_fill_color(ctx, command->fill_color); gpath_draw_filled(ctx, &path); } if ((command->stroke_color.a != 0) && (command->stroke_width > 0)) { graphics_context_set_stroke_color(ctx, command->stroke_color); graphics_context_set_stroke_width(ctx, command->stroke_width); gpath_draw_stroke(ctx, &path, command->path_open); } } static void prv_draw_circle(GContext *ctx, GDrawCommand *command) { // draw all values of alpha, except fully transparent if ((command->fill_color.a != 0) && (command->radius > 0)) { graphics_context_set_fill_color(ctx, command->fill_color); graphics_fill_circle(ctx, command->points[0], command->radius); } if ((command->stroke_color.a != 0) && (command->stroke_width > 0)) { graphics_context_set_stroke_color(ctx, command->stroke_color); graphics_context_set_stroke_width(ctx, command->stroke_width); graphics_draw_circle(ctx, command->points[0], command->radius); } } static void prv_draw_precise_path(GContext *ctx, GDrawCommand *command) { if (command->num_points <= 1) { return; } // draw all values of alpha, except fully transparent if ((command->fill_color.a != 0)) { graphics_context_set_fill_color(ctx, command->fill_color); gpath_fill_precise_internal(ctx, command->precise_points, command->num_precise_points); } if ((command->stroke_color.a != 0) && (command->stroke_width > 0)) { graphics_context_set_stroke_color(ctx, command->stroke_color); graphics_context_set_stroke_width(ctx, command->stroke_width); gpath_draw_outline_precise_internal(ctx, command->precise_points, command->num_precise_points, command->path_open); } } void gdraw_command_draw(GContext *ctx, GDrawCommand *command) { if (!command || command->hidden) { return; } switch (command->type) { case GDrawCommandTypePath:
prv_draw_path(ctx, command)
<|repo_name|>pebble <|file_sep|>src/fw/applib/graphics/gdraw_command.c <|fim_prefix|> "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "applib/applib_resource_private.h" #include "gdraw_command.h" #include "gdraw_command_private.h" #include "applib/applib_malloc.auto.h" #include "applib/graphics/gpath.h" #include "system/passert.h" #include "syscall/syscall.h" #include "util/net.h" bool gdraw_command_resource_is_valid(ResAppNum app_num, uint32_t resource_id, uint32_t expected_signature, uint32_t *data_size) { // Load file signature, and check that it matches the expected_signature uint32_t data_signature; if (!(sys_resource_load_range(app_num, resource_id, 0, (uint8_t*)&data_signature, sizeof(data_signature)) == sizeof(data_signature) && (ntohl(data_signature) == expected_signature))) { return NULL; } // Data is the second entry after the resource signature if (data_size) { uint32_t output_data_size; _Static_assert(PDCI_SIZE_OFFSET == PDCS_SIZE_OFFSET, "code re-use between PDCI/PDCS requires same file format header"); if (sys_resource_load_range(app_num, resource_id, sizeof(expected_signature), (uint8_t*)&output_data_size, sizeof(output_data_size)) != sizeof(output_data_size)) { return NULL; } *data_size = output_data_size; } return true; } bool gdraw_command_validate(GDrawCommand *command, size_t size) { if ((size < gdraw_command_get_data_size(command))) { return false; } return (((command->type == GDrawCommandTypeCircle) && (command->num_points == 1)) || ((command->type == GDrawCommandTypePath) && (command->num_points > 1)) || ((command->type == GDrawCommandTypePrecisePath) && (command->num_points > 1))); } static void prv_draw_path(GContext *ctx, GDrawCommand *command) { if (command->num_points <= 1) { return; } GPath path = { .num_points = command->num_points, .points = command->points }; // draw all values of alpha, except fully transparent if ((command->fill_color.a != 0)) { graphics_context_set_fill_color(ctx, command->fill_color); gpath_draw_filled(ctx, &path); } if ((command->stroke_color.a != 0) && (command->stroke_width > 0)) { graphics_context_set_stroke_color(ctx, command->stroke_color); graphics_context_set_stroke_width(ctx, command->stroke_width); gpath_draw_stroke(ctx, &path, command->path_open); } } static void prv_draw_circle(GContext *ctx, GDrawCommand *command) { // draw all values of alpha, except fully transparent if ((command->fill_color.a != 0) && (command->radius > 0)) { graphics_context_set_fill_color(ctx, command->fill_color); graphics_fill_circle(ctx, command->points[0], command->radius); } if ((command->stroke_color.a != 0) && (command->stroke_width > 0)) { graphics_context_set_stroke_color(ctx, command->stroke_color); graphics_context_set_stroke_width(ctx, command->stroke_width); graphics_draw_circle(ctx, command->points[0], command->radius); } } static void prv_draw_precise_path(GContext *ctx, GDrawCommand *command) { if (command->num_points <= 1) { return; } // draw all values of alpha, except fully transparent if ((command->fill_color.a != 0)) { graphics_context_set_fill_color(ctx, command->fill_color); gpath_fill_precise_internal(ctx, command->precise_points, command->num_precise_points); } if ((command->stroke_color.a != 0) && (command->stroke_width > 0)) { graphics_context_set_stroke_color(ctx, command->stroke_color); graphics_context_set_stroke_width(ctx, command->stroke_width); gpath_draw_outline_precise_internal(ctx, command->precise_points, command->num_precise_points, command->path_open); } } void gdraw_command_draw(GContext *ctx, GDrawCommand *command) { if (!command || command->hidden) { return; } switch (command->type) { case GDrawCommandTypePath: <|fim_suffix|><|fim_middle|>prv_draw_path(ctx, command)<|endoftext|>
prefix_only
argument_list
tests/fw/services/test_timeline_item.c
}, { .id = 1, .type = TimelineItemActionTypeHttp }, { .id = 2, .type = TimelineItemActionTypeOpenPin }, }; void test_timeline_item__find_action_with_id(void) { // Make sure we're resilient to NULL items cl_assert_equal_p(timeline_item_find_action_with_id(NULL, 0), NULL); // Make sure we can handle timeline items with no actions TimelineItem item = {}; cl_assert_equal_p(timeline_item_find_action_with_id(&item, 0), NULL); // Make sure we actually find the items we're looking for item.action_group.num_actions = ARRAY_LENGTH(s_basic_action_list); item.action_group.actions = s_basic_action_list; cl_assert_equal_p(timeline_item_find_action_with_id(&item, 0), &s_basic_action_list[0]); cl_assert_equal_p(timeline_item_find_action_with_id(&item, 1), &s_basic_action_list[1]); cl_assert_equal_p(timeline_item_find_action_with_id(&item, 2), &s_basic_action_list[2]); cl_assert_equal_p(timeline_item_find_action_with_id(&item, 3), NULL); item.header.id = UUID_INVALID; cl_assert_equal_p(timeline_item_find_action_with_id(&item, 0), NULL); } void test_timeline_item__find_action_by_type(void) { // Make sure we're resilient to NULL items cl_assert_equal_p(timeline_item_find_action_by_type(NULL, TimelineItemActionTypeGeneric), NULL); // Make sure we can handle timeline items with no actions TimelineItem item = {}; cl_assert_equal_p(timeline_item_find_action_by_type(&item, TimelineItemActionTypeGeneric), NULL); // Make sure we actually find the items we're looking for item.action_group.num_actions = ARRAY_LENGTH(s_basic_action_list); item.action_group.actions = s_basic_action_list; cl_assert_equal_p(timeline_item_find_action_by_type(&item, TimelineItemActionTypeGeneric), &s_basic_action_list[0]); cl_assert_equal_p(timeline_item_find_action_by_type(&item, TimelineItemActionTypeHttp), &s_basic_action_list[1]); cl_assert_equal_p(timeline_item_find_action_by_type(&item, TimelineItemActionTypeOpenPin), &s_basic_action_list[2]); cl_assert_equal_p(timeline_item_find_action_by_type(&item, TimelineItemActionTypeRemove), NULL); item.header.id = UUID_INVALID; cl_assert_equal_p(timeline_item_find_action_by_type(&item, 0), NULL); } void test_timeline_item__find_dismiss_action(void) { // Make sure we're resilient to NULL items cl_assert_equal_p(timeline_item_find_dismiss_action(NULL), NULL); // Make sure we can handle timeline items with no actions TimelineItem item = {}; cl_assert_equal_p(timeline_item_find_dismiss_action(&item), NULL); // Copy the action list since it's easiest to just modify it TimelineItemAction *action_list = malloc(sizeof(s_basic_action_list)); memcpy(action_list, s_basic_action_list, sizeof(s_basic_action_list)); item.action_group.num_actions = ARRAY_LENGTH(s_basic_action_list); item.action_group.actions = action_list; // Make sure we don't return anything if the action doesn't exist cl_assert_equal_p(timeline_item_find_dismiss_action(&item), NULL); // Make sure we find both dismiss and ancs negative actions action_list[1].type = TimelineItemActionTypeDismiss; cl_assert_equal_p(timeline_item_find_dismiss_action(&item), &action_list[1]); action_list[1].type = TimelineItemActionTypeAncsNegative; cl_assert_equal_p(timeline_item_find_dismiss_action(&item), &action_list[1]); item.header.id = UUID_INVALID; cl_assert_equal_p(timeline_item_find_dismiss_action(&item), NULL); free(action_list); } void test_timeline_item__find_reply_action(void) { // Make sure we're resilient to NULL items cl_assert_equal_p(timeline_item_find_reply_action(NULL), NULL); // Make sure we can handle timeline items with no actions TimelineItem item = {}; cl_assert_equal_p(timeline_item_find_reply_action(&item), NULL); // Copy the action list since it's easiest to just modify it TimelineItemAction *action_list = malloc(sizeof(s_basic_action_list)); memcpy(action_list, s_basic_action_list, sizeof(s_basic_action_list)); item.action_group.num_actions = ARRAY_LENGTH
(s_basic_action_list)
<|repo_name|>pebble <|file_sep|>tests/fw/services/test_timeline_item.c <|fim_prefix|>}, { .id = 1, .type = TimelineItemActionTypeHttp }, { .id = 2, .type = TimelineItemActionTypeOpenPin }, }; void test_timeline_item__find_action_with_id(void) { // Make sure we're resilient to NULL items cl_assert_equal_p(timeline_item_find_action_with_id(NULL, 0), NULL); // Make sure we can handle timeline items with no actions TimelineItem item = {}; cl_assert_equal_p(timeline_item_find_action_with_id(&item, 0), NULL); // Make sure we actually find the items we're looking for item.action_group.num_actions = ARRAY_LENGTH(s_basic_action_list); item.action_group.actions = s_basic_action_list; cl_assert_equal_p(timeline_item_find_action_with_id(&item, 0), &s_basic_action_list[0]); cl_assert_equal_p(timeline_item_find_action_with_id(&item, 1), &s_basic_action_list[1]); cl_assert_equal_p(timeline_item_find_action_with_id(&item, 2), &s_basic_action_list[2]); cl_assert_equal_p(timeline_item_find_action_with_id(&item, 3), NULL); item.header.id = UUID_INVALID; cl_assert_equal_p(timeline_item_find_action_with_id(&item, 0), NULL); } void test_timeline_item__find_action_by_type(void) { // Make sure we're resilient to NULL items cl_assert_equal_p(timeline_item_find_action_by_type(NULL, TimelineItemActionTypeGeneric), NULL); // Make sure we can handle timeline items with no actions TimelineItem item = {}; cl_assert_equal_p(timeline_item_find_action_by_type(&item, TimelineItemActionTypeGeneric), NULL); // Make sure we actually find the items we're looking for item.action_group.num_actions = ARRAY_LENGTH(s_basic_action_list); item.action_group.actions = s_basic_action_list; cl_assert_equal_p(timeline_item_find_action_by_type(&item, TimelineItemActionTypeGeneric), &s_basic_action_list[0]); cl_assert_equal_p(timeline_item_find_action_by_type(&item, TimelineItemActionTypeHttp), &s_basic_action_list[1]); cl_assert_equal_p(timeline_item_find_action_by_type(&item, TimelineItemActionTypeOpenPin), &s_basic_action_list[2]); cl_assert_equal_p(timeline_item_find_action_by_type(&item, TimelineItemActionTypeRemove), NULL); item.header.id = UUID_INVALID; cl_assert_equal_p(timeline_item_find_action_by_type(&item, 0), NULL); } void test_timeline_item__find_dismiss_action(void) { // Make sure we're resilient to NULL items cl_assert_equal_p(timeline_item_find_dismiss_action(NULL), NULL); // Make sure we can handle timeline items with no actions TimelineItem item = {}; cl_assert_equal_p(timeline_item_find_dismiss_action(&item), NULL); // Copy the action list since it's easiest to just modify it TimelineItemAction *action_list = malloc(sizeof(s_basic_action_list)); memcpy(action_list, s_basic_action_list, sizeof(s_basic_action_list)); item.action_group.num_actions = ARRAY_LENGTH(s_basic_action_list); item.action_group.actions = action_list; // Make sure we don't return anything if the action doesn't exist cl_assert_equal_p(timeline_item_find_dismiss_action(&item), NULL); // Make sure we find both dismiss and ancs negative actions action_list[1].type = TimelineItemActionTypeDismiss; cl_assert_equal_p(timeline_item_find_dismiss_action(&item), &action_list[1]); action_list[1].type = TimelineItemActionTypeAncsNegative; cl_assert_equal_p(timeline_item_find_dismiss_action(&item), &action_list[1]); item.header.id = UUID_INVALID; cl_assert_equal_p(timeline_item_find_dismiss_action(&item), NULL); free(action_list); } void test_timeline_item__find_reply_action(void) { // Make sure we're resilient to NULL items cl_assert_equal_p(timeline_item_find_reply_action(NULL), NULL); // Make sure we can handle timeline items with no actions TimelineItem item = {}; cl_assert_equal_p(timeline_item_find_reply_action(&item), NULL); // Copy the action list since it's easiest to just modify it TimelineItemAction *action_list = malloc(sizeof(s_basic_action_list)); memcpy(action_list, s_basic_action_list, sizeof(s_basic_action_list)); item.action_group.num_actions = ARRAY_LENGTH<|fim_suffix|><|fim_middle|>(s_basic_action_list)<|endoftext|>
masked_node
argument_list
src/fw/applib/pbl_std/pbl_std.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "applib/pbl_std/pbl_std.h" #include "applib/app_logging.h" #include "applib/applib_malloc.auto.h" #include "process_state/app_state/app_state.h" #include "process_state/worker_state/worker_state.h" #include "syscall/syscall.h" #include "syscall/syscall_internal.h" // Time time_t pbl_override_time(time_t *tloc) { time_t t = sys_get_time(); if (tloc) { *tloc = t; } return (t); } // Manually construct double to avoid requiring soft-fp static double prv_time_to_double(time_t time) { // time_t is 32bit signed int, convert it manually #ifndef UNITTEST _Static_assert(sizeof(time_t) == 4, "Conversion depends on 32bit time_t"); #endif if (time == 0) { return 0; } // Construct the double in two uint32_t's then reinterpret as double // Using a uint64_t would pull in helper functions for 64bit shifts union { double result; uint32_t representation[2]; } conv; conv.representation[1] = 0; if (time < 0) { // set the sign bit conv.representation[1] |= (1 << 31); // sign bit takes care of positive vs negative time *= -1; } uint32_t significand = (uint32_t)time; // In order to normalize the significand, we shift off all the leading 0s // plus the msb which is implicitly included int shift = __builtin_clz(time) + 1; significand <<= shift; // top 20 bits fit into the upper 32 bits of the double conv.representation[1] |= (significand >> 12); // bottom 12 bits go into the lower 32 bits of the double conv.representation[0] = (significand << 20); // Exponent is biased by 1023, then adjusted for the amount the significand was // shifted. Out of the 52 significand bits, the bottom 20 are never used. uint32_t exp = 1023 + 52 - shift - 20; // Set the exponent conv.representation[1] |= (exp << 20); return conv.result; } double pbl_override_difftime(time_t end, time_t beginning) { return prv_time_to_double(end - beginning); } time_t pbl_override_time_legacy(time_t *tloc) { time_t t = sys_get_time(); time_t legacy_time = sys_time_utc_to_local(t); if (tloc) { *tloc = legacy_time; } return (legacy_time); } DEFINE_SYSCALL(time_t, pbl_override_mktime, struct tm *tb) { if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer
; } return mktime(tb); } uint16_t time_ms(time_t *tloc, uint16_t *out_ms) { uint16_t t_ms; time_t t_s; sys_get_time_ms(&t_s, &t_ms); if (out_ms) { *out_ms = t_ms; } if (tloc) { *tloc = t_s; } return (t_ms); } uint16_t pbl_override_time_ms_legacy(time_t *tloc, uint16_t *out_ms) { uint16_t t_ms; time_t t_s; sys_get_time_ms(&t_s, &t_ms); time_t legacy_time = sys_time_utc_to_local(t_s); if (out_ms) { *out_ms = t_ms; } if (tloc) { *tloc = legacy_time; } return (t_ms); } extern size_t localized_strftime(char* s, size_t maxsize, const char* format, const struct tm* tim_p, const char *locale); struct tm *pbl_override_gmtime(const time_t *timep) { struct tm *gmtime_tm = NULL; if (pebble_task_get_current() == PebbleTask_App) { gmtime_tm = app_state_get_gmtime_tm(); } else { gmtime_tm = worker_state_get_gmtime_tm(); } sys_gmtime_r(timep, gmtime_tm); return gmtime_tm; } struct tm *pbl_override_localtime(const time_t *timep) { struct tm *localtime_tm = NULL; char *localtime_zone = NULL; if (pebble_task_get_current() == PebbleTask_App) { localtime_tm = app_state_get_localtime_tm(); localtime_zone = app_state_get_localtime_zone(); } else { localtime_tm = worker_state_get_localtime_tm(); localtime_zone = worker_state_get_localtime_zone(); } sys_localtime_r(timep, localtime_tm); // We have to work around localtime_r resetting tm_zone below sys_copy_timezone_abbr((char*)localtime_zone, *timep); strncpy(localtime_tm->tm_zone, localtime_zone, TZ_LEN); return localtime_tm; } int pbl_strftime(char* s, size_t maxsize, const char* format, const struct tm* tim_p) { char *locale = app_state_get_locale_info()->app_locale_time; return sys_strftime(s, maxsize, format, tim_p, locale); } DEFINE_SYSCALL(int, sys_strftime, char* s, size_t maxsize, const char* format, const struct tm* tim_p, char *locale) { if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer(s, maxsize); syscall_assert_userspace_buffer(format, strlen(format)); syscall_assert_userspace_buffer(tim_p, sizeof(struct tm)); } return localized_strftime(s, maxsize, format, tim_p, locale); } void *pbl_memcpy(void *destination, const void *source, size_t num) { // In releases prior to FW 2.5 we used GCC 4.7 and newlib as our libc implementation. However, // in 2.5 we switched to GCC 4.8 and nano-newlib. We actually ran into bad apps that would pass // negative numbers as their num parameter, which newlib handled by copying nothing, but // newlib-nano didn't handle at all and would interpret size_t as a extremely large unsigned // number. Guard against this happening so apps that used to work with the old libc will work // with the new libc. See PBL-7873. if (((ptrdiff_t) num) <= 0) { return destination; } return memcpy(destination, source, num); } // Formatted printing. The ROM's libc library (newlib) is compiled without // floating point support in order to save space. Because of this, you can // get an exception and a OS reset if an app tries to use %f or any of the // other floating point format types in an snprintf call. This is because the // implementation does not advance the va_arg (pointer to arguments on the // stack) pointer when it sees one of these FP types and will thus end up using // that floating point argument as the argument for the *next* format type. If // the next format type is a string for example, you end up with a bus error // when it tries to use that argument as a pointer. // // To prevent an OS reset, we scan the format string here and bail with an // APP_LOG message if we detect an attempt to use floating point. We also // return a "floating point not supported" string in the passed in str // buffer. int pbl_snprintf(char * str, size_t n, const char * format, ...) { int ret; const char* fp_msg = "floating point not supported in snprintf"; // Scan string and see if it has any floating point specifiers in it bool has_fp = false
(tb, sizeof(struct tm))
<|repo_name|>pebble <|file_sep|>src/fw/applib/pbl_std/pbl_std.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "applib/pbl_std/pbl_std.h" #include "applib/app_logging.h" #include "applib/applib_malloc.auto.h" #include "process_state/app_state/app_state.h" #include "process_state/worker_state/worker_state.h" #include "syscall/syscall.h" #include "syscall/syscall_internal.h" // Time time_t pbl_override_time(time_t *tloc) { time_t t = sys_get_time(); if (tloc) { *tloc = t; } return (t); } // Manually construct double to avoid requiring soft-fp static double prv_time_to_double(time_t time) { // time_t is 32bit signed int, convert it manually #ifndef UNITTEST _Static_assert(sizeof(time_t) == 4, "Conversion depends on 32bit time_t"); #endif if (time == 0) { return 0; } // Construct the double in two uint32_t's then reinterpret as double // Using a uint64_t would pull in helper functions for 64bit shifts union { double result; uint32_t representation[2]; } conv; conv.representation[1] = 0; if (time < 0) { // set the sign bit conv.representation[1] |= (1 << 31); // sign bit takes care of positive vs negative time *= -1; } uint32_t significand = (uint32_t)time; // In order to normalize the significand, we shift off all the leading 0s // plus the msb which is implicitly included int shift = __builtin_clz(time) + 1; significand <<= shift; // top 20 bits fit into the upper 32 bits of the double conv.representation[1] |= (significand >> 12); // bottom 12 bits go into the lower 32 bits of the double conv.representation[0] = (significand << 20); // Exponent is biased by 1023, then adjusted for the amount the significand was // shifted. Out of the 52 significand bits, the bottom 20 are never used. uint32_t exp = 1023 + 52 - shift - 20; // Set the exponent conv.representation[1] |= (exp << 20); return conv.result; } double pbl_override_difftime(time_t end, time_t beginning) { return prv_time_to_double(end - beginning); } time_t pbl_override_time_legacy(time_t *tloc) { time_t t = sys_get_time(); time_t legacy_time = sys_time_utc_to_local(t); if (tloc) { *tloc = legacy_time; } return (legacy_time); } DEFINE_SYSCALL(time_t, pbl_override_mktime, struct tm *tb) { if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer<|fim_suffix|>; } return mktime(tb); } uint16_t time_ms(time_t *tloc, uint16_t *out_ms) { uint16_t t_ms; time_t t_s; sys_get_time_ms(&t_s, &t_ms); if (out_ms) { *out_ms = t_ms; } if (tloc) { *tloc = t_s; } return (t_ms); } uint16_t pbl_override_time_ms_legacy(time_t *tloc, uint16_t *out_ms) { uint16_t t_ms; time_t t_s; sys_get_time_ms(&t_s, &t_ms); time_t legacy_time = sys_time_utc_to_local(t_s); if (out_ms) { *out_ms = t_ms; } if (tloc) { *tloc = legacy_time; } return (t_ms); } extern size_t localized_strftime(char* s, size_t maxsize, const char* format, const struct tm* tim_p, const char *locale); struct tm *pbl_override_gmtime(const time_t *timep) { struct tm *gmtime_tm = NULL; if (pebble_task_get_current() == PebbleTask_App) { gmtime_tm = app_state_get_gmtime_tm(); } else { gmtime_tm = worker_state_get_gmtime_tm(); } sys_gmtime_r(timep, gmtime_tm); return gmtime_tm; } struct tm *pbl_override_localtime(const time_t *timep) { struct tm *localtime_tm = NULL; char *localtime_zone = NULL; if (pebble_task_get_current() == PebbleTask_App) { localtime_tm = app_state_get_localtime_tm(); localtime_zone = app_state_get_localtime_zone(); } else { localtime_tm = worker_state_get_localtime_tm(); localtime_zone = worker_state_get_localtime_zone(); } sys_localtime_r(timep, localtime_tm); // We have to work around localtime_r resetting tm_zone below sys_copy_timezone_abbr((char*)localtime_zone, *timep); strncpy(localtime_tm->tm_zone, localtime_zone, TZ_LEN); return localtime_tm; } int pbl_strftime(char* s, size_t maxsize, const char* format, const struct tm* tim_p) { char *locale = app_state_get_locale_info()->app_locale_time; return sys_strftime(s, maxsize, format, tim_p, locale); } DEFINE_SYSCALL(int, sys_strftime, char* s, size_t maxsize, const char* format, const struct tm* tim_p, char *locale) { if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer(s, maxsize); syscall_assert_userspace_buffer(format, strlen(format)); syscall_assert_userspace_buffer(tim_p, sizeof(struct tm)); } return localized_strftime(s, maxsize, format, tim_p, locale); } void *pbl_memcpy(void *destination, const void *source, size_t num) { // In releases prior to FW 2.5 we used GCC 4.7 and newlib as our libc implementation. However, // in 2.5 we switched to GCC 4.8 and nano-newlib. We actually ran into bad apps that would pass // negative numbers as their num parameter, which newlib handled by copying nothing, but // newlib-nano didn't handle at all and would interpret size_t as a extremely large unsigned // number. Guard against this happening so apps that used to work with the old libc will work // with the new libc. See PBL-7873. if (((ptrdiff_t) num) <= 0) { return destination; } return memcpy(destination, source, num); } // Formatted printing. The ROM's libc library (newlib) is compiled without // floating point support in order to save space. Because of this, you can // get an exception and a OS reset if an app tries to use %f or any of the // other floating point format types in an snprintf call. This is because the // implementation does not advance the va_arg (pointer to arguments on the // stack) pointer when it sees one of these FP types and will thus end up using // that floating point argument as the argument for the *next* format type. If // the next format type is a string for example, you end up with a bus error // when it tries to use that argument as a pointer. // // To prevent an OS reset, we scan the format string here and bail with an // APP_LOG message if we detect an attempt to use floating point. We also // return a "floating point not supported" string in the passed in str // buffer. int pbl_snprintf(char * str, size_t n, const char * format, ...) { int ret; const char* fp_msg = "floating point not supported in snprintf"; // Scan string and see if it has any floating point specifiers in it bool has_fp = false<|fim_middle|>(tb, sizeof(struct tm))<|endoftext|>
prefix_only
call_expression
tests/libc/time/test_strftime.c
.tm_gmtoff = 4200; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "+0110"); jan_2_2015__13_00_00.tm_gmtoff = 36000; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "+1000"); jan_2_2015__13_00_00.tm_gmtoff = 39600; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "+1100"); jan_2_2015__13_00_00.tm_gmtoff = -60; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); #if !OUR_STRFTIME_BUGS cl_assert_equal_s(tmbuf, "-0001"); #else // BUG!! cl_assert_equal_s(tmbuf, "+0001"); #endif jan_2_2015__13_00_00.tm_gmtoff = -600; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); #if !OUR_STRFTIME_BUGS cl_assert_equal_s(tmbuf, "-0010"); #else // BUG!! cl_assert_equal_s(tmbuf, "+0010"); #endif jan_2_2015__13_00_00.tm_gmtoff = -3600; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "-0100"); jan_2_2015__13_00_00.tm_gmtoff = -4200; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "-0110"); jan_2_2015__13_00_00.tm_gmtoff = -36000; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "-1000"); jan_2_2015__13_00_00.tm_gmtoff = -39600; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "-1100"); } #endif void test_strftime__full_percent_U(void) { char tmbuf[512]; struct tm dec_30_2014__13_00_00 = { .tm_hour = 13, .tm_min = 0, .tm_sec = 0, // 13:00:00 .tm_year = 2014 - 1900, .tm_mon = 11, .tm_mday = 30, // 2014/12/30 .tm_wday = 2, .tm_yday = 363, // Tuesday, 364th day of the year .tm_gmtoff = 0, .tm_isdst = 0, .tm_zone = "UTC", // No DST, UTC+0 }; struct tm jan_2_2015__13_00_00 = { .tm_hour = 13, .tm_min = 0, .tm_sec = 0, // 13:00:00 .tm_year = 2015 - 1900, .tm_mon = 0, .tm_mday = 2, // 2015/01/02 .tm_wday = 5, .tm_yday = 1, // Friday, 2nd day of the year .tm_gmtoff = 0, .tm_isdst = 0, .tm_zone = "UTC", // No DST, UTC+0 }; struct tm jan_1_2016__13_00_00 = { .tm_hour = 13, .tm_min = 0, .tm_sec = 0, // 13:00:00 .tm_year = 2016 - 1900, .tm_mon = 0, .tm_mday = 1, // 2016/01/01 .tm_wday = 5, .tm_yday = 0, // Friday, 1st day of the year .tm_gmtoff = 0, .tm_isdst = 0, .tm_zone = "UTC", // No DST, UTC+0 }; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%U", &dec_30_2014__13_00_00); cl_assert_equal_s(tmbuf, "52"); tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%U", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "00"); tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%U", &jan_1_2016__13_00_00); cl_assert_equal_s(tmbuf, "00"); } // Test the zero flag void test_strftime__zeroflag(void) { char tmbuf[512]; struct tm jan_2_10015__13_00_00 = { .tm_hour = 13, .tm_min = 0, .tm_sec = 0, // 13:00:00 .tm_year = 10015 - 1900, .tm_mon = 0, .tm_mday = 2, // 10015/01/02 .tm_wday = 5, .tm_yday = 1, // Friday, 2nd day of the year .tm_gmtoff = 0, .tm_isdst = 0, .tm_zone = "UTC", // No DST, UTC+0 }; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%02a %01A %06b %04B", &jan_2_10015__13_00_00); cl_assert_equal_s(tmbuf, "Fri Friday Jan January"); tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%06c", &jan_2_10015__13_00_00); cl_assert_equal_s(tmbuf, "Fri Jan 2 13:00:00 10015"); #if EXTENSION_SU tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%0C %01h", &jan_2_10015__13_00_00); cl_assert_equal_s(tmbuf, "100 Jan"); tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%02D %04e", &jan_2_10015__13_00_00); cl_assert_equal_s(tmbuf, "01/02/15 0002"); tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%05n %03r", &jan_2_10015__13_00_00); cl_assert_equal_s(tmbuf, "\n 01:00:00 PM"); tmbuf[0] = '\0';
strftime(tmbuf, sizeof(tmbuf), "%02R %06t %04T", &jan_2_10015__13_00_00)
<|repo_name|>pebble <|file_sep|>tests/libc/time/test_strftime.c <|fim_prefix|>.tm_gmtoff = 4200; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "+0110"); jan_2_2015__13_00_00.tm_gmtoff = 36000; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "+1000"); jan_2_2015__13_00_00.tm_gmtoff = 39600; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "+1100"); jan_2_2015__13_00_00.tm_gmtoff = -60; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); #if !OUR_STRFTIME_BUGS cl_assert_equal_s(tmbuf, "-0001"); #else // BUG!! cl_assert_equal_s(tmbuf, "+0001"); #endif jan_2_2015__13_00_00.tm_gmtoff = -600; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); #if !OUR_STRFTIME_BUGS cl_assert_equal_s(tmbuf, "-0010"); #else // BUG!! cl_assert_equal_s(tmbuf, "+0010"); #endif jan_2_2015__13_00_00.tm_gmtoff = -3600; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "-0100"); jan_2_2015__13_00_00.tm_gmtoff = -4200; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "-0110"); jan_2_2015__13_00_00.tm_gmtoff = -36000; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "-1000"); jan_2_2015__13_00_00.tm_gmtoff = -39600; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%z", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "-1100"); } #endif void test_strftime__full_percent_U(void) { char tmbuf[512]; struct tm dec_30_2014__13_00_00 = { .tm_hour = 13, .tm_min = 0, .tm_sec = 0, // 13:00:00 .tm_year = 2014 - 1900, .tm_mon = 11, .tm_mday = 30, // 2014/12/30 .tm_wday = 2, .tm_yday = 363, // Tuesday, 364th day of the year .tm_gmtoff = 0, .tm_isdst = 0, .tm_zone = "UTC", // No DST, UTC+0 }; struct tm jan_2_2015__13_00_00 = { .tm_hour = 13, .tm_min = 0, .tm_sec = 0, // 13:00:00 .tm_year = 2015 - 1900, .tm_mon = 0, .tm_mday = 2, // 2015/01/02 .tm_wday = 5, .tm_yday = 1, // Friday, 2nd day of the year .tm_gmtoff = 0, .tm_isdst = 0, .tm_zone = "UTC", // No DST, UTC+0 }; struct tm jan_1_2016__13_00_00 = { .tm_hour = 13, .tm_min = 0, .tm_sec = 0, // 13:00:00 .tm_year = 2016 - 1900, .tm_mon = 0, .tm_mday = 1, // 2016/01/01 .tm_wday = 5, .tm_yday = 0, // Friday, 1st day of the year .tm_gmtoff = 0, .tm_isdst = 0, .tm_zone = "UTC", // No DST, UTC+0 }; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%U", &dec_30_2014__13_00_00); cl_assert_equal_s(tmbuf, "52"); tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%U", &jan_2_2015__13_00_00); cl_assert_equal_s(tmbuf, "00"); tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%U", &jan_1_2016__13_00_00); cl_assert_equal_s(tmbuf, "00"); } // Test the zero flag void test_strftime__zeroflag(void) { char tmbuf[512]; struct tm jan_2_10015__13_00_00 = { .tm_hour = 13, .tm_min = 0, .tm_sec = 0, // 13:00:00 .tm_year = 10015 - 1900, .tm_mon = 0, .tm_mday = 2, // 10015/01/02 .tm_wday = 5, .tm_yday = 1, // Friday, 2nd day of the year .tm_gmtoff = 0, .tm_isdst = 0, .tm_zone = "UTC", // No DST, UTC+0 }; tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%02a %01A %06b %04B", &jan_2_10015__13_00_00); cl_assert_equal_s(tmbuf, "Fri Friday Jan January"); tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%06c", &jan_2_10015__13_00_00); cl_assert_equal_s(tmbuf, "Fri Jan 2 13:00:00 10015"); #if EXTENSION_SU tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%0C %01h", &jan_2_10015__13_00_00); cl_assert_equal_s(tmbuf, "100 Jan"); tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%02D %04e", &jan_2_10015__13_00_00); cl_assert_equal_s(tmbuf, "01/02/15 0002"); tmbuf[0] = '\0'; strftime(tmbuf, sizeof(tmbuf), "%05n %03r", &jan_2_10015__13_00_00); cl_assert_equal_s(tmbuf, "\n 01:00:00 PM"); tmbuf[0] = '\0'; <|fim_suffix|><|fim_middle|>strftime(tmbuf, sizeof(tmbuf), "%02R %06t %04T", &jan_2_10015__13_00_00)<|endoftext|>
masked_node
call_expression
src/fw/services/normal/activity/activity_insights.c
_config->detail_text, &pin_attr_list); } else { detail_text = config->detail_text; } attribute_list_add_cstring(&pin_attr_list, PBL_IF_RECT_ELSE(AttributeIdLocationName, AttributeIdTitle), detail_text); attribute_list_add_cstring(&pin_attr_list, AttributeIdBody, i18n_get(percent_config->body, &pin_attr_list)); attribute_list_add_resource_id(&pin_attr_list, AttributeIdIconTiny, config->icon); attribute_list_add_resource_id(&pin_attr_list, AttributeIdIconSmall, s_tier_config[tier].card_icon); attribute_list_add_uint8(&pin_attr_list, AttributeIdDisplayTime, WeatherTimeType_None); attribute_list_add_uint32(&pin_attr_list, AttributeIdLastUpdated, now_utc); char *percentage_buf = kernel_malloc_check(SUBTITLE_BUFFER_LENGTH); if (percentage == 0) { strcpy(percentage_buf, "0%"); } else { sniprintf(percentage_buf, SUBTITLE_BUFFER_LENGTH, "%+d%%", percentage); } attribute_list_add_cstring(&pin_attr_list, AttributeIdSubtitle, percentage_buf); TimelineItem *item = prv_create_pin(pin_time_utc, now_utc, 0, LayoutIdWeather, &pin_attr_list, config->health_card_type); kernel_free(percentage_buf); i18n_free_all(&pin_attr_list); attribute_list_destroy_list(&pin_attr_list); return item; } // ------------------------------------------------------------------------------------------------ // Inserts a new pin on the timeline if existing_uuid is UUID_INVALID, otherwise the pin is updated // Returns true if it added a new pin, false if it updated static bool prv_push_pin(TimelineItem *item, Uuid *existing_uuid) { bool rv = false; if (item) { item->header.from_watch = true; item->header.parent_id = (Uuid)UUID_HEALTH_DATA_SOURCE; if (!uuid_is_invalid(existing_uuid)) { item->header.id = *existing_uuid; } else { *existing_uuid = item->header.id; rv = true; } timeline_add(item); timeline_item_destroy(item); } return rv; } // ------------------------------------------------------------------------------------------------ static bool prv_push_summary_pin(time_t pin_time_utc, time_t now_utc, Uuid *existing_uuid, ActivityScalarStore cur_val, ActivityScalarStore average, const SummaryPinConfig *config) { TimelineItem *item = prv_create_summary_pin(pin_time_utc, now_utc, cur_val, average, config); return prv_push_pin(item, existing_uuid); } // ------------------------------------------------------------------------------------------------ // Pushes a new reward notification and saves the trigger time to flash static void prv_push_reward(time_t now_utc, const RewardNotifConfig *notif_config) { prv_push_reward_notification(now_utc, notif_config); notif_config->state->last_triggered_utc = time_util_get_midnight_of(now_utc); analytics_event_health_insight_created(now_utc, notif_config->insight_type, 0); // Save out the trigger time prv_save_state(notif_config->settings_key, &notif_config->state->last_triggered_utc, sizeof(notif_config->state->last_triggered_utc)); INSIGHTS_LOG_DEBUG("Saved reward state: %ld", notif_config->state->last_triggered_utc); } // ------------------------------------------------------------------------------------------------ // Filter for calculating metric history stats (values <= 0 are considered invalid) static bool prv_stats_filter(int index, int32_t value, void *context) { return (value > 0); } // ------------------------------------------------------------------------------------------------ // Calculates the mean and median of a metric over the entire history we have for it and counts the // total and consecutive days of history T_STATIC void prv_calculate_metric_history_stats(ActivityMetric metric, ActivityInsightMetricHistoryStats *stats) { int32_t *history =
; activity_get_metric(metric, ACTIVITY_HISTORY_DAYS, history); const StatsBasicOp op = (StatsBasicOp_Average | StatsBasicOp_Count | StatsBasicOp_ConsecutiveFirst | StatsBasicOp_Median); struct { int32_t mean; int32_t count; int32_t first_streak; int32_t median; } result; // Note: we ignore history[0] since it's the current day stats_calculate_basic(op, &history[1], ACTIVITY_HISTORY_DAYS - 1, prv_stats_filter, NULL, &result.mean); *stats = (ActivityInsightMetricHistoryStats) { .metric = metric, .mean = result.mean, .total_days = result.count, .consecutive_days = result.first_streak, .median = result.median, }; kernel_free(history); INSIGHTS_LOG_DEBUG("Metric history stats - med: %"PRIu16" mean: %"PRIu16" tot: %"PRIu8 " cons: %"PRIu8, stats->median, stats->mean, stats->total_days, stats->consecutive_days); } // ----------------------------------------------------------------------------------------------- // Validates history stats for a given metric against insight settings static bool prv_validate_history_stats(const ActivityInsightMetricHistoryStats *stats, const ActivityInsightSettings *insight_settings) { // Make sure we have enough history if ((stats->total_days < insight_settings->reward.min_days_data) || (stats->consecutive_days < insight_settings->reward.continuous_min_days_data)) { INSIGHTS_LOG_DEBUG("History validation failed - total/consecutive days didn't match: " "%"PRIu8" %"PRIu8, stats->total_days, stats->consecutive_days); return false; } // We want to look at the x days before today (which is always index 0), so add 1 uint32_t history_len = insight_settings->reward.target_qualifying_days + 1; if (history_len > ACTIVITY_HISTORY_DAYS) { PBL_LOG(LOG_LEVEL_ERROR, "Insight qualifying history length is too long: %"PRIu32, history_len); return false; } ActivityScalarStore target = ((uint32_t)(stats->median * insight_settings->reward.target_percent_of_median)) / 100; int32_t history[history_len]; activity_get_metric(stats->metric, history_len, history); // Make sure enough days have been above the target // (start at 1 since we don't care about today's metric) for (uint32_t i = 1; i < history_len; ++i) { if (history[i] < target) { INSIGHTS_LOG_DEBUG("History validation failed - not above target on day %"PRIu32 ": %"PRIi32, i, history[i]); return false; } } return true; } // ------------------------------------------------------------------------------------------------ static TimelineItem *prv_create_day_1_insight(time_t notif_time) { if (activity_prefs_get_health_app_opened_version() != 0) { // The user already knows about the Health app return NULL; } AttributeList notif_attr_list = {0}; const char *body = i18n_get("Wanna know more about you? " "Track your activity and sleep with Pebble Health.", &notif_attr_list); prv_build_notification_attr_list(&notif_attr_list, body, TIMELINE_RESOURCE_ACTIVITY, ActivityInsightType_Day1, ActivitySessionType_None); AttributeList dismiss_action_attr_list = {0}; attribute_list_add_cstring(&dismiss_action_attr_list, AttributeIdTitle, i18n_get("Dismiss", &notif_attr_list)); AttributeList open_app_action_attr_list = {0}; prv_set_open_app_action(&open_app_action_attr_list, HealthCardType_Activity, &notif_attr_list); const int num_actions = 2; TimelineItemActionGroup action_group = { .num_actions = num_actions, .actions = (TimelineItemAction[]) { { .id = 0, .type = TimelineItemActionTypeDismiss, .attr_list = dismiss_action_attr_list, }, { .id = 1, .type = TimelineItemActionTypeOpenWatchApp, .attr_list = open
kernel_malloc_check(sizeof(int32_t[ACTIVITY_HISTORY_DAYS]))
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/activity/activity_insights.c <|fim_prefix|>_config->detail_text, &pin_attr_list); } else { detail_text = config->detail_text; } attribute_list_add_cstring(&pin_attr_list, PBL_IF_RECT_ELSE(AttributeIdLocationName, AttributeIdTitle), detail_text); attribute_list_add_cstring(&pin_attr_list, AttributeIdBody, i18n_get(percent_config->body, &pin_attr_list)); attribute_list_add_resource_id(&pin_attr_list, AttributeIdIconTiny, config->icon); attribute_list_add_resource_id(&pin_attr_list, AttributeIdIconSmall, s_tier_config[tier].card_icon); attribute_list_add_uint8(&pin_attr_list, AttributeIdDisplayTime, WeatherTimeType_None); attribute_list_add_uint32(&pin_attr_list, AttributeIdLastUpdated, now_utc); char *percentage_buf = kernel_malloc_check(SUBTITLE_BUFFER_LENGTH); if (percentage == 0) { strcpy(percentage_buf, "0%"); } else { sniprintf(percentage_buf, SUBTITLE_BUFFER_LENGTH, "%+d%%", percentage); } attribute_list_add_cstring(&pin_attr_list, AttributeIdSubtitle, percentage_buf); TimelineItem *item = prv_create_pin(pin_time_utc, now_utc, 0, LayoutIdWeather, &pin_attr_list, config->health_card_type); kernel_free(percentage_buf); i18n_free_all(&pin_attr_list); attribute_list_destroy_list(&pin_attr_list); return item; } // ------------------------------------------------------------------------------------------------ // Inserts a new pin on the timeline if existing_uuid is UUID_INVALID, otherwise the pin is updated // Returns true if it added a new pin, false if it updated static bool prv_push_pin(TimelineItem *item, Uuid *existing_uuid) { bool rv = false; if (item) { item->header.from_watch = true; item->header.parent_id = (Uuid)UUID_HEALTH_DATA_SOURCE; if (!uuid_is_invalid(existing_uuid)) { item->header.id = *existing_uuid; } else { *existing_uuid = item->header.id; rv = true; } timeline_add(item); timeline_item_destroy(item); } return rv; } // ------------------------------------------------------------------------------------------------ static bool prv_push_summary_pin(time_t pin_time_utc, time_t now_utc, Uuid *existing_uuid, ActivityScalarStore cur_val, ActivityScalarStore average, const SummaryPinConfig *config) { TimelineItem *item = prv_create_summary_pin(pin_time_utc, now_utc, cur_val, average, config); return prv_push_pin(item, existing_uuid); } // ------------------------------------------------------------------------------------------------ // Pushes a new reward notification and saves the trigger time to flash static void prv_push_reward(time_t now_utc, const RewardNotifConfig *notif_config) { prv_push_reward_notification(now_utc, notif_config); notif_config->state->last_triggered_utc = time_util_get_midnight_of(now_utc); analytics_event_health_insight_created(now_utc, notif_config->insight_type, 0); // Save out the trigger time prv_save_state(notif_config->settings_key, &notif_config->state->last_triggered_utc, sizeof(notif_config->state->last_triggered_utc)); INSIGHTS_LOG_DEBUG("Saved reward state: %ld", notif_config->state->last_triggered_utc); } // ------------------------------------------------------------------------------------------------ // Filter for calculating metric history stats (values <= 0 are considered invalid) static bool prv_stats_filter(int index, int32_t value, void *context) { return (value > 0); } // ------------------------------------------------------------------------------------------------ // Calculates the mean and median of a metric over the entire history we have for it and counts the // total and consecutive days of history T_STATIC void prv_calculate_metric_history_stats(ActivityMetric metric, ActivityInsightMetricHistoryStats *stats) { int32_t *history = <|fim_suffix|>; activity_get_metric(metric, ACTIVITY_HISTORY_DAYS, history); const StatsBasicOp op = (StatsBasicOp_Average | StatsBasicOp_Count | StatsBasicOp_ConsecutiveFirst | StatsBasicOp_Median); struct { int32_t mean; int32_t count; int32_t first_streak; int32_t median; } result; // Note: we ignore history[0] since it's the current day stats_calculate_basic(op, &history[1], ACTIVITY_HISTORY_DAYS - 1, prv_stats_filter, NULL, &result.mean); *stats = (ActivityInsightMetricHistoryStats) { .metric = metric, .mean = result.mean, .total_days = result.count, .consecutive_days = result.first_streak, .median = result.median, }; kernel_free(history); INSIGHTS_LOG_DEBUG("Metric history stats - med: %"PRIu16" mean: %"PRIu16" tot: %"PRIu8 " cons: %"PRIu8, stats->median, stats->mean, stats->total_days, stats->consecutive_days); } // ----------------------------------------------------------------------------------------------- // Validates history stats for a given metric against insight settings static bool prv_validate_history_stats(const ActivityInsightMetricHistoryStats *stats, const ActivityInsightSettings *insight_settings) { // Make sure we have enough history if ((stats->total_days < insight_settings->reward.min_days_data) || (stats->consecutive_days < insight_settings->reward.continuous_min_days_data)) { INSIGHTS_LOG_DEBUG("History validation failed - total/consecutive days didn't match: " "%"PRIu8" %"PRIu8, stats->total_days, stats->consecutive_days); return false; } // We want to look at the x days before today (which is always index 0), so add 1 uint32_t history_len = insight_settings->reward.target_qualifying_days + 1; if (history_len > ACTIVITY_HISTORY_DAYS) { PBL_LOG(LOG_LEVEL_ERROR, "Insight qualifying history length is too long: %"PRIu32, history_len); return false; } ActivityScalarStore target = ((uint32_t)(stats->median * insight_settings->reward.target_percent_of_median)) / 100; int32_t history[history_len]; activity_get_metric(stats->metric, history_len, history); // Make sure enough days have been above the target // (start at 1 since we don't care about today's metric) for (uint32_t i = 1; i < history_len; ++i) { if (history[i] < target) { INSIGHTS_LOG_DEBUG("History validation failed - not above target on day %"PRIu32 ": %"PRIi32, i, history[i]); return false; } } return true; } // ------------------------------------------------------------------------------------------------ static TimelineItem *prv_create_day_1_insight(time_t notif_time) { if (activity_prefs_get_health_app_opened_version() != 0) { // The user already knows about the Health app return NULL; } AttributeList notif_attr_list = {0}; const char *body = i18n_get("Wanna know more about you? " "Track your activity and sleep with Pebble Health.", &notif_attr_list); prv_build_notification_attr_list(&notif_attr_list, body, TIMELINE_RESOURCE_ACTIVITY, ActivityInsightType_Day1, ActivitySessionType_None); AttributeList dismiss_action_attr_list = {0}; attribute_list_add_cstring(&dismiss_action_attr_list, AttributeIdTitle, i18n_get("Dismiss", &notif_attr_list)); AttributeList open_app_action_attr_list = {0}; prv_set_open_app_action(&open_app_action_attr_list, HealthCardType_Activity, &notif_attr_list); const int num_actions = 2; TimelineItemActionGroup action_group = { .num_actions = num_actions, .actions = (TimelineItemAction[]) { { .id = 0, .type = TimelineItemActionTypeDismiss, .attr_list = dismiss_action_attr_list, }, { .id = 1, .type = TimelineItemActionTypeOpenWatchApp, .attr_list = open<|fim_middle|>kernel_malloc_check(sizeof(int32_t[ACTIVITY_HISTORY_DAYS]))<|endoftext|>
masked_node
argument_list
src/fw/apps/system_apps/settings/settings_system.c
ppending_regulatory_compliance_marks(cd); if (flags->has_japan_telec_r) { prv_append_certification_menu(cd, &(SystemCertificationMenuItem) { .draw_cell_fn = prv_draw_rt_cell, .arg1 = &cd->r_mark, .arg2 = prv_get_japan_telec_r_id() }); } if (flags->has_japan_telec_t) { prv_append_certification_menu(cd, &(SystemCertificationMenuItem) { .draw_cell_fn = prv_draw_rt_cell, .arg1 = &cd->t_mark, .arg2 = prv_get_japan_telec_t_id() }); } // Create the menu MenuLayer *menu_layer = &data->menu_layer; GRect bounds = data->window.layer.bounds; const GEdgeInsets menu_layer_insets = (GEdgeInsets) { .top = STATUS_BAR_LAYER_HEIGHT, .bottom = PBL_IF_RECT_ELSE(0, STATUS_BAR_LAYER_HEIGHT) }; bounds = grect_inset(bounds, menu_layer_insets); menu_layer_init(menu_layer, &bounds); menu_layer_set_callbacks(menu_layer, data, &(MenuLayerCallbacks) { .get_num_rows = prv_certification_get_num_rows_callback, .get_cell_height = prv_certification_get_cell_height_callback, .draw_row = prv_certification_draw_row_callback, .select_click = prv_certification_select_callback, }); menu_layer_set_highlight_colors(menu_layer, SETTINGS_MENU_HIGHLIGHT_COLOR, GColorWhite); menu_layer_set_click_config_onto_window(menu_layer, &data->window); layer_add_child(&data->window.layer, menu_layer_get_layer(menu_layer)); } static void prv_certification_window_unload(Window *window) { SettingsSystemData *data = (SettingsSystemData*) window_get_user_data(window); menu_layer_deinit(&data->menu_layer); gbitmap_deinit(&data->certification_data.fcc_mark); gbitmap_deinit(&data->certification_data.kcc_mark); gbitmap_deinit(&data->certification_data.ce_mark); gbitmap_deinit(&data->certification_data.weee_mark); gbitmap_deinit(&data->certification_data.r_mark); gbitmap_deinit(&data->certification_data.t_mark); gbitmap_deinit(&data->certification_data.aus_rcm_mark); gbitmap_deinit(&data->certification_data.nom_nyce_mark); app_free(data->certification_data.regulatory_marks); app_free(data->certification_data.menu_items); prv_deinit_status_bar(&data->status_layer); } static void prv_certification_window_push(SettingsSystemData *data) { window_init(&data->window, WINDOW_NAME("System Certification")); window_set_user_data(&data->window, data); window_set_window_handlers(&data->window, &(WindowHandlers) { .load = prv_certification_window_load, .unload = prv_certification_window_unload, }); app_window_stack_push(&data->window, true); } static void prv_kcc_window_load(Window *window) { SystemCertificationData *data = (SystemCertificationData *) window_get_user_data(window); Layer *window_layer = window_get_root_layer(window); const char *title = "South Korea KCC"; prv_init_status_bar(&data->status_layer, &data->kcc_window, title); GRect window_bounds = window_layer->bounds; // Calculate the bounding rect for the certification content and center it in the window GBitmap *bmp = &data->kcc_mark; const GSize bmp_size = bmp->bounds.size; const GFont title_text_font = fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD); const GSize title_text_size = GSize(window_bounds.size.w, fonts_get_font_height(title_text_font)); const GFont info_text_font = fonts_get_system_font(FONT_KEY_GOTHIC_14); const GSize info_text_size = GSize(window_bounds.size.w, fonts_get_font_height(info_text_font)); const int16_t vertical_spacing = 3; GRect certification_rect = (GRect) { .size = GSize(window_bounds.size.w, bmp_size.h + title_text_size.h + info_text_size.h + vertical_spacing) }; grect_align(&certification_rect, &window_bounds, GAlignCenter, true /* clip */); GRect bmp_frame = (GRect) { .size = bmp_size }; grect_align(&bmp_frame, &certification_rect, GAlignTop, true /* clip */); bitmap_layer_init(&data->bmp_layer, &bmp_frame); bitmap_layer_set_bitmap(&data->bmp_layer, bmp); bitmap_layer_set_compositing_mode(&data->bmp_layer, GCompOpAssign); layer_add_child
; GRect title_text_frame = (GRect) { .size = title_text_size }; const int16_t title_text_internal_padding = 5; title_text_frame.origin.y = bmp_frame.origin.y + bmp_size.h + vertical_spacing - title_text_internal_padding; text_layer_init_with_parameters(&data->title_text, &title_text_frame, title, title_text_font, GColorBlack, GColorClear, GTextAlignmentCenter, GTextOverflowModeTrailingEllipsis); layer_add_child(window_layer, text_layer_get_layer(&data->title_text)); GRect info_text_frame = (GRect) { .size = info_text_size }; info_text_frame.origin.y = title_text_frame.origin.y + title_text_size.h + vertical_spacing; text_layer_init_with_parameters(&data->info_text, &info_text_frame, prv_get_korea_kcc_id(), info_text_font, GColorBlack, GColorClear, GTextAlignmentCenter, GTextOverflowModeTrailingEllipsis); layer_add_child(window_layer, text_layer_get_layer(&data->info_text)); } static void prv_kcc_window_unload(Window *window) { SystemCertificationData *data = (SystemCertificationData *) window_get_user_data(window); prv_deinit_status_bar(&data->status_layer); bitmap_layer_deinit(&data->bmp_layer); text_layer_deinit(&data->title_text); text_layer_deinit(&data->info_text); i18n_free_all(data); } static void prv_push_kcc_window(SystemCertificationData *data) { window_init(&data->kcc_window, WINDOW_NAME("System KCC")); window_set_user_data(&data->kcc_window, data); window_set_window_handlers(&data->kcc_window, &(WindowHandlers) { .load = prv_kcc_window_load, .unload = prv_kcc_window_unload, }); app_window_stack_push(&data->kcc_window, true); } // Callbacks for the main settings filter list menu. //////////////////////////////////////////////////// #define SHUTDOWN_MIN_BOOT_VERSION 1354647953 static bool prv_shutdown_enabled(void) { return boot_version_read() >= SHUTDOWN_MIN_BOOT_VERSION; } static void prv_shutdown_confirm_cb(ClickRecognizerRef recognizer, void *context) { actionable_dialog_pop((ActionableDialog *) context); battery_ui_handle_shut_down(); } static void prv_shutdown_back_cb(ClickRecognizerRef recognizer, void *context) { actionable_dialog_pop((ActionableDialog *) context); } static void prv_shutdown_click_provider(void *context) { window_single_click_subscribe(BUTTON_ID_SELECT, prv_shutdown_confirm_cb); window_single_click_subscribe(BUTTON_ID_BACK, prv_shutdown_back_cb); } static void prv_shutdown_cb(void* data) { ActionableDialog *a_dialog = actionable_dialog_create("Shutdown"); Dialog *dialog = actionable_dialog_get_dialog(a_dialog); actionable_dialog_set_action_bar_type(a_dialog, DialogActionBarConfirm, NULL); actionable_dialog_set_click_config_provider(a_dialog, prv_shutdown_click_provider); dialog_set_text_color(dialog, GColorWhite); dialog_set_background_color(dialog, GColorCobaltBlue); dialog_set_text(dialog, i18n_get("Do you want to shut down?", a_dialog)); dialog_set_icon(dialog, RESOURCE_ID_GENERIC_QUESTION_LARGE); i18n_free_all(a_dialog); actionable_dialog_push(a_dialog, modal_manager_get_window_stack(ModalPriorityGeneric)); } static void prv_deinit_cb(SettingsCallbacks *context) { SettingsSystemData *data = (SettingsSystemData *) context; i18n_free_all(data); } static void prv_draw_row_cb(SettingsCallbacks *context, GContext *ctx, const Layer *cell_layer, uint16_t row, bool selected) { SettingsSystemData *data = (SettingsSystemData *) context; const char *subtitle = NULL; PBL_ASSERTN(row < SystemMenuItem_Count); switch (row) { case SystemMenuItemStationaryToggle: subtitle = stationary_get_enabled() ? i18n_get("On", data) : i18n_get("Off", data); break; case SystemMenuItemShutDown: if (!prv_shutdown_enabled()) { // XXX: For now, gray out the Shut Down item if unusable.
(window_layer, bitmap_layer_get_layer(&data->bmp_layer))
<|repo_name|>pebble <|file_sep|>src/fw/apps/system_apps/settings/settings_system.c <|fim_prefix|>ppending_regulatory_compliance_marks(cd); if (flags->has_japan_telec_r) { prv_append_certification_menu(cd, &(SystemCertificationMenuItem) { .draw_cell_fn = prv_draw_rt_cell, .arg1 = &cd->r_mark, .arg2 = prv_get_japan_telec_r_id() }); } if (flags->has_japan_telec_t) { prv_append_certification_menu(cd, &(SystemCertificationMenuItem) { .draw_cell_fn = prv_draw_rt_cell, .arg1 = &cd->t_mark, .arg2 = prv_get_japan_telec_t_id() }); } // Create the menu MenuLayer *menu_layer = &data->menu_layer; GRect bounds = data->window.layer.bounds; const GEdgeInsets menu_layer_insets = (GEdgeInsets) { .top = STATUS_BAR_LAYER_HEIGHT, .bottom = PBL_IF_RECT_ELSE(0, STATUS_BAR_LAYER_HEIGHT) }; bounds = grect_inset(bounds, menu_layer_insets); menu_layer_init(menu_layer, &bounds); menu_layer_set_callbacks(menu_layer, data, &(MenuLayerCallbacks) { .get_num_rows = prv_certification_get_num_rows_callback, .get_cell_height = prv_certification_get_cell_height_callback, .draw_row = prv_certification_draw_row_callback, .select_click = prv_certification_select_callback, }); menu_layer_set_highlight_colors(menu_layer, SETTINGS_MENU_HIGHLIGHT_COLOR, GColorWhite); menu_layer_set_click_config_onto_window(menu_layer, &data->window); layer_add_child(&data->window.layer, menu_layer_get_layer(menu_layer)); } static void prv_certification_window_unload(Window *window) { SettingsSystemData *data = (SettingsSystemData*) window_get_user_data(window); menu_layer_deinit(&data->menu_layer); gbitmap_deinit(&data->certification_data.fcc_mark); gbitmap_deinit(&data->certification_data.kcc_mark); gbitmap_deinit(&data->certification_data.ce_mark); gbitmap_deinit(&data->certification_data.weee_mark); gbitmap_deinit(&data->certification_data.r_mark); gbitmap_deinit(&data->certification_data.t_mark); gbitmap_deinit(&data->certification_data.aus_rcm_mark); gbitmap_deinit(&data->certification_data.nom_nyce_mark); app_free(data->certification_data.regulatory_marks); app_free(data->certification_data.menu_items); prv_deinit_status_bar(&data->status_layer); } static void prv_certification_window_push(SettingsSystemData *data) { window_init(&data->window, WINDOW_NAME("System Certification")); window_set_user_data(&data->window, data); window_set_window_handlers(&data->window, &(WindowHandlers) { .load = prv_certification_window_load, .unload = prv_certification_window_unload, }); app_window_stack_push(&data->window, true); } static void prv_kcc_window_load(Window *window) { SystemCertificationData *data = (SystemCertificationData *) window_get_user_data(window); Layer *window_layer = window_get_root_layer(window); const char *title = "South Korea KCC"; prv_init_status_bar(&data->status_layer, &data->kcc_window, title); GRect window_bounds = window_layer->bounds; // Calculate the bounding rect for the certification content and center it in the window GBitmap *bmp = &data->kcc_mark; const GSize bmp_size = bmp->bounds.size; const GFont title_text_font = fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD); const GSize title_text_size = GSize(window_bounds.size.w, fonts_get_font_height(title_text_font)); const GFont info_text_font = fonts_get_system_font(FONT_KEY_GOTHIC_14); const GSize info_text_size = GSize(window_bounds.size.w, fonts_get_font_height(info_text_font)); const int16_t vertical_spacing = 3; GRect certification_rect = (GRect) { .size = GSize(window_bounds.size.w, bmp_size.h + title_text_size.h + info_text_size.h + vertical_spacing) }; grect_align(&certification_rect, &window_bounds, GAlignCenter, true /* clip */); GRect bmp_frame = (GRect) { .size = bmp_size }; grect_align(&bmp_frame, &certification_rect, GAlignTop, true /* clip */); bitmap_layer_init(&data->bmp_layer, &bmp_frame); bitmap_layer_set_bitmap(&data->bmp_layer, bmp); bitmap_layer_set_compositing_mode(&data->bmp_layer, GCompOpAssign); layer_add_child<|fim_suffix|>; GRect title_text_frame = (GRect) { .size = title_text_size }; const int16_t title_text_internal_padding = 5; title_text_frame.origin.y = bmp_frame.origin.y + bmp_size.h + vertical_spacing - title_text_internal_padding; text_layer_init_with_parameters(&data->title_text, &title_text_frame, title, title_text_font, GColorBlack, GColorClear, GTextAlignmentCenter, GTextOverflowModeTrailingEllipsis); layer_add_child(window_layer, text_layer_get_layer(&data->title_text)); GRect info_text_frame = (GRect) { .size = info_text_size }; info_text_frame.origin.y = title_text_frame.origin.y + title_text_size.h + vertical_spacing; text_layer_init_with_parameters(&data->info_text, &info_text_frame, prv_get_korea_kcc_id(), info_text_font, GColorBlack, GColorClear, GTextAlignmentCenter, GTextOverflowModeTrailingEllipsis); layer_add_child(window_layer, text_layer_get_layer(&data->info_text)); } static void prv_kcc_window_unload(Window *window) { SystemCertificationData *data = (SystemCertificationData *) window_get_user_data(window); prv_deinit_status_bar(&data->status_layer); bitmap_layer_deinit(&data->bmp_layer); text_layer_deinit(&data->title_text); text_layer_deinit(&data->info_text); i18n_free_all(data); } static void prv_push_kcc_window(SystemCertificationData *data) { window_init(&data->kcc_window, WINDOW_NAME("System KCC")); window_set_user_data(&data->kcc_window, data); window_set_window_handlers(&data->kcc_window, &(WindowHandlers) { .load = prv_kcc_window_load, .unload = prv_kcc_window_unload, }); app_window_stack_push(&data->kcc_window, true); } // Callbacks for the main settings filter list menu. //////////////////////////////////////////////////// #define SHUTDOWN_MIN_BOOT_VERSION 1354647953 static bool prv_shutdown_enabled(void) { return boot_version_read() >= SHUTDOWN_MIN_BOOT_VERSION; } static void prv_shutdown_confirm_cb(ClickRecognizerRef recognizer, void *context) { actionable_dialog_pop((ActionableDialog *) context); battery_ui_handle_shut_down(); } static void prv_shutdown_back_cb(ClickRecognizerRef recognizer, void *context) { actionable_dialog_pop((ActionableDialog *) context); } static void prv_shutdown_click_provider(void *context) { window_single_click_subscribe(BUTTON_ID_SELECT, prv_shutdown_confirm_cb); window_single_click_subscribe(BUTTON_ID_BACK, prv_shutdown_back_cb); } static void prv_shutdown_cb(void* data) { ActionableDialog *a_dialog = actionable_dialog_create("Shutdown"); Dialog *dialog = actionable_dialog_get_dialog(a_dialog); actionable_dialog_set_action_bar_type(a_dialog, DialogActionBarConfirm, NULL); actionable_dialog_set_click_config_provider(a_dialog, prv_shutdown_click_provider); dialog_set_text_color(dialog, GColorWhite); dialog_set_background_color(dialog, GColorCobaltBlue); dialog_set_text(dialog, i18n_get("Do you want to shut down?", a_dialog)); dialog_set_icon(dialog, RESOURCE_ID_GENERIC_QUESTION_LARGE); i18n_free_all(a_dialog); actionable_dialog_push(a_dialog, modal_manager_get_window_stack(ModalPriorityGeneric)); } static void prv_deinit_cb(SettingsCallbacks *context) { SettingsSystemData *data = (SettingsSystemData *) context; i18n_free_all(data); } static void prv_draw_row_cb(SettingsCallbacks *context, GContext *ctx, const Layer *cell_layer, uint16_t row, bool selected) { SettingsSystemData *data = (SettingsSystemData *) context; const char *subtitle = NULL; PBL_ASSERTN(row < SystemMenuItem_Count); switch (row) { case SystemMenuItemStationaryToggle: subtitle = stationary_get_enabled() ? i18n_get("On", data) : i18n_get("Off", data); break; case SystemMenuItemShutDown: if (!prv_shutdown_enabled()) { // XXX: For now, gray out the Shut Down item if unusable. <|fim_middle|>(window_layer, bitmap_layer_get_layer(&data->bmp_layer))<|endoftext|>
masked_node
call_expression
tests/fw/mfg/test_spalding_mfg_info.c
cleanup(void) { fake_spi_flash_cleanup(); } void test_spalding_mfg_info__color(void) { cl_assert_equal_i(mfg_info_get_watch_color(), 0); mfg_info_set_watch_color(WATCH_INFO_COLOR_RED); cl_assert_equal_i(mfg_info_get_watch_color(), WATCH_INFO_COLOR_RED); mfg_info_set_watch_color(WATCH_INFO_COLOR_GREEN); cl_assert_equal_i(mfg_info_get_watch_color(), WATCH_INFO_COLOR_GREEN); } void test_spalding_mfg_info__rtc_freq(void) { cl_assert_equal_i(mfg_info_get_rtc_freq(), 0); mfg_info_set_rtc_freq(0xfefefefe); cl_assert_equal_i(mfg_info_get_rtc_freq(), 0xfefefefe); mfg_info_set_rtc_freq(1337); cl_assert_equal_i(mfg_info_get_rtc_freq(), 1337); } void test_spalding_mfg_info__model(void) { // Intentionally make the buffer too long so we can check for truncation. char buffer[MFG_INFO_MODEL_STRING_LENGTH + 1] = { 0 }; mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); mfg_info_set_model("test_model"); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, "test_model"); { char long_string[] = "01234567890123456789"; mfg_info_set_model(long_string); // We only expect to see the first 15 (MFG_INFO_MODEL_STRING_LENGTH - 1) characters mfg_info_get_model(buffer); cl_assert_equal_s(buffer, "012345678901234"); } } void test_spalding_mfg_info__1_to_2_conversion(void) { // Force in an old data version. typedef struct { uint32_t data_version; uint32_t color; uint32_t rtc_freq; } MfgDataV1; MfgDataV1 old_data = { .data_version = 1, .color = 3, .rtc_freq = 4 }; flash_write_bytes((const uint8_t*) &old_data, FLASH_REGION_MFG_INFO_BEGIN, sizeof(old_data)); // Now use the info functions to read the data and make sure it's sane. A conversion will have // happened behind the scenes to the latest version. cl_assert_equal_i(mfg_info_get_watch_color(), 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); char buffer[MFG_INFO_MODEL_STRING_LENGTH] = { 0 }; mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); // Set color and make sure others don't change. mfg_info_set_watch_color(5); cl_assert_equal_i(mfg_info_get_watch_color(), 5); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); // Make sure we have space for the model. mfg_info_set_model("test_model"); cl_assert_equal_i(mfg_info_get_watch_color(), 5); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, "test_model"); } void test_spalding_mfg_info__1_to_3_conversion(void) { // Force in an old data version. typedef struct { uint32_t data_version; uint32_t color; uint32_t rtc_freq; } MfgDataV1; MfgDataV1 old_data = { .data_version = 1, .color = 3, .rtc_freq = 4 }; flash_write_bytes((const uint8_t*) &old_data, FLASH_REGION_MFG_INFO_BEGIN, sizeof(old_data)); // Now use the info functions to read the data and make sure it's sane. A conversion will have // happened behind the scenes to the latest version. cl_assert_equal_i(mfg_info_get_watch_color(), 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); char buffer[MFG_INFO_MODEL_STRING_LENGTH] = { 0 }; mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); cl_assert_equal_i(mfg_info_get_disp_offsets().x, 0); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 0); // Set x and y offsets and make sure others don't change. mfg_info_set_disp_offsets((GPoint) {-2, 1}); cl_assert_equal_i(mfg_info_get_disp_offsets().x, -2); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 1); cl_assert_equal_i(mfg_info_get_watch_color(), 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); // Make sure we have space for the model. mfg_info_set_model("test_model"); cl_assert_equal_i(mfg_info_get_disp_offsets().x, -2); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 1); cl_assert_equal_i(
, 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, "test_model"); } void test_spalding_mfg_info__2_to_3_conversion(void) { // Force in an old data version. typedef struct { uint32_t data_version; uint32_t color; uint32_t rtc_freq; char model[MFG_INFO_MODEL_STRING_LENGTH]; } MfgDataV2; MfgDataV2 old_data = { .data_version = 1, .color = 3, .rtc_freq = 4, .model[0] = '\0' }; flash_write_bytes((const uint8_t*) &old_data, FLASH_REGION_MFG_INFO_BEGIN, sizeof(old_data)); // Now use the info functions to read the data and make sure it's sane. A conversion will have // happened behind the scenes to the latest version. cl_assert_equal_i(mfg_info_get_watch_color(), 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); char buffer[MFG_INFO_MODEL_STRING_LENGTH] = { 0 }; mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); cl_assert_equal_i(mfg_info_get_disp_offsets().x, 0); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 0); // Set x and y offsets and make sure others don't change. mfg_info_set_disp_offsets((GPoint) {-2, 1}); cl_assert_equal_i(mfg_info_get_disp_offsets().x, -2); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 1); cl_assert_equal_i(mfg_info_get_watch_color(), 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); // Make sure we have space for the model. mfg_info_set_model("test_model"); cl_assert_equal_i(mfg_info_get_disp_offsets().x, -2); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 1); cl_assert_equal_i(mfg_info_get_watch_color(), 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, "test_model"); } void test_spalding_mfg_info__boot_fpga_persistence(void) { // Make sure no FPGA image is stored const uintptr_t BOOT_FPGA_FLASH_ADDR = FLASH_REGION_MFG_INFO_BEGIN + 0x10000; const uint32_t HEADER_SIZE = 4; // sizeof(BootFPGAHeader) uint8_t fpga_buffer[HEADER_SIZE + sizeof(s_boot_fpga)]; flash_read_bytes(fpga_buffer, BOOT_FPGA_FLASH_ADDR, sizeof(fpga_buffer)); for (int i = 0; i < sizeof(s_boot_fpga); ++i) { cl_assert(fpga_buffer[i] == 0xff); } // Write some data in mfg_info_set_rtc_freq(1); // The first time we write something into mfg_info we'll actually write the boot fpga as a side // effect. Make sure it's there. flash_read_bytes(fpga_buffer, BOOT_FPGA_FLASH_ADDR, sizeof(fpga_buffer)); cl_assert(memcmp(fpga_buffer + HEADER_SIZE, s_boot_fpga, sizeof(s_boot_fpga)) == 0); mfg_info_set_disp_offsets((GPoint) { 2, 3 }); char model[MFG_INFO_MODEL_STRING_LENGTH] = "123456789012345"; mfg_info_set_model(model); // Now let's write in an fpga image mfg_info_update_constant_data(); // Let's make sure the mfg data is still persisted cl_assert_equal_i(mfg_info_get_rtc_freq(), 1); cl_assert_equal_i(mfg_info_get_disp_offsets().x, 2); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 3); char result_model[MFG_INFO_MODEL_STRING_LENGTH]; mfg_info_get_model(result_model); cl_assert_equal_s(model, result_model); // Make sure the boot fpga is still correct flash_read_bytes(fpga_buffer, BOOT_FPGA_FLASH_ADDR, sizeof(fpga_buffer)); cl_assert(memcmp(fpga_buffer + HEADER_SIZE, s_boot_fpga, sizeof(s_boot_fpga)) == 0); // Now invalidate the section and write it back. Make sure it comes back flash_write_bytes((const uint8_t*) "xxxx", BOOT_FPGA_FLASH_ADDR + HEADER_SIZE, 4); // Make sure it's corrupted flash_read_bytes(fpga_buffer, BOOT_FPGA_FLASH_ADDR, sizeof(fpga_buffer)); cl_assert(memcmp(fpga_buffer + HEADER_SIZE, s_boot_fpga, sizeof(s_boot_fpga)) != 0); // Now update it and make sure we healed the corruption mfg_info_update_constant_data(); flash_read_bytes(fpga_buffer, BOOT_FPGA_FLASH_ADDR, sizeof(fpga_buffer)); cl_assert(memcmp(fpga_buffer + HEADER_SIZE, s_boot_fpga, sizeof(s_boot_fpga)) == 0); }
mfg_info_get_watch_color()
<|repo_name|>pebble <|file_sep|>tests/fw/mfg/test_spalding_mfg_info.c <|fim_prefix|>cleanup(void) { fake_spi_flash_cleanup(); } void test_spalding_mfg_info__color(void) { cl_assert_equal_i(mfg_info_get_watch_color(), 0); mfg_info_set_watch_color(WATCH_INFO_COLOR_RED); cl_assert_equal_i(mfg_info_get_watch_color(), WATCH_INFO_COLOR_RED); mfg_info_set_watch_color(WATCH_INFO_COLOR_GREEN); cl_assert_equal_i(mfg_info_get_watch_color(), WATCH_INFO_COLOR_GREEN); } void test_spalding_mfg_info__rtc_freq(void) { cl_assert_equal_i(mfg_info_get_rtc_freq(), 0); mfg_info_set_rtc_freq(0xfefefefe); cl_assert_equal_i(mfg_info_get_rtc_freq(), 0xfefefefe); mfg_info_set_rtc_freq(1337); cl_assert_equal_i(mfg_info_get_rtc_freq(), 1337); } void test_spalding_mfg_info__model(void) { // Intentionally make the buffer too long so we can check for truncation. char buffer[MFG_INFO_MODEL_STRING_LENGTH + 1] = { 0 }; mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); mfg_info_set_model("test_model"); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, "test_model"); { char long_string[] = "01234567890123456789"; mfg_info_set_model(long_string); // We only expect to see the first 15 (MFG_INFO_MODEL_STRING_LENGTH - 1) characters mfg_info_get_model(buffer); cl_assert_equal_s(buffer, "012345678901234"); } } void test_spalding_mfg_info__1_to_2_conversion(void) { // Force in an old data version. typedef struct { uint32_t data_version; uint32_t color; uint32_t rtc_freq; } MfgDataV1; MfgDataV1 old_data = { .data_version = 1, .color = 3, .rtc_freq = 4 }; flash_write_bytes((const uint8_t*) &old_data, FLASH_REGION_MFG_INFO_BEGIN, sizeof(old_data)); // Now use the info functions to read the data and make sure it's sane. A conversion will have // happened behind the scenes to the latest version. cl_assert_equal_i(mfg_info_get_watch_color(), 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); char buffer[MFG_INFO_MODEL_STRING_LENGTH] = { 0 }; mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); // Set color and make sure others don't change. mfg_info_set_watch_color(5); cl_assert_equal_i(mfg_info_get_watch_color(), 5); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); // Make sure we have space for the model. mfg_info_set_model("test_model"); cl_assert_equal_i(mfg_info_get_watch_color(), 5); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, "test_model"); } void test_spalding_mfg_info__1_to_3_conversion(void) { // Force in an old data version. typedef struct { uint32_t data_version; uint32_t color; uint32_t rtc_freq; } MfgDataV1; MfgDataV1 old_data = { .data_version = 1, .color = 3, .rtc_freq = 4 }; flash_write_bytes((const uint8_t*) &old_data, FLASH_REGION_MFG_INFO_BEGIN, sizeof(old_data)); // Now use the info functions to read the data and make sure it's sane. A conversion will have // happened behind the scenes to the latest version. cl_assert_equal_i(mfg_info_get_watch_color(), 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); char buffer[MFG_INFO_MODEL_STRING_LENGTH] = { 0 }; mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); cl_assert_equal_i(mfg_info_get_disp_offsets().x, 0); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 0); // Set x and y offsets and make sure others don't change. mfg_info_set_disp_offsets((GPoint) {-2, 1}); cl_assert_equal_i(mfg_info_get_disp_offsets().x, -2); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 1); cl_assert_equal_i(mfg_info_get_watch_color(), 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); // Make sure we have space for the model. mfg_info_set_model("test_model"); cl_assert_equal_i(mfg_info_get_disp_offsets().x, -2); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 1); cl_assert_equal_i(<|fim_suffix|>, 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, "test_model"); } void test_spalding_mfg_info__2_to_3_conversion(void) { // Force in an old data version. typedef struct { uint32_t data_version; uint32_t color; uint32_t rtc_freq; char model[MFG_INFO_MODEL_STRING_LENGTH]; } MfgDataV2; MfgDataV2 old_data = { .data_version = 1, .color = 3, .rtc_freq = 4, .model[0] = '\0' }; flash_write_bytes((const uint8_t*) &old_data, FLASH_REGION_MFG_INFO_BEGIN, sizeof(old_data)); // Now use the info functions to read the data and make sure it's sane. A conversion will have // happened behind the scenes to the latest version. cl_assert_equal_i(mfg_info_get_watch_color(), 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); char buffer[MFG_INFO_MODEL_STRING_LENGTH] = { 0 }; mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); cl_assert_equal_i(mfg_info_get_disp_offsets().x, 0); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 0); // Set x and y offsets and make sure others don't change. mfg_info_set_disp_offsets((GPoint) {-2, 1}); cl_assert_equal_i(mfg_info_get_disp_offsets().x, -2); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 1); cl_assert_equal_i(mfg_info_get_watch_color(), 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, ""); // Make sure we have space for the model. mfg_info_set_model("test_model"); cl_assert_equal_i(mfg_info_get_disp_offsets().x, -2); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 1); cl_assert_equal_i(mfg_info_get_watch_color(), 3); cl_assert_equal_i(mfg_info_get_rtc_freq(), 4); mfg_info_get_model(buffer); cl_assert_equal_s(buffer, "test_model"); } void test_spalding_mfg_info__boot_fpga_persistence(void) { // Make sure no FPGA image is stored const uintptr_t BOOT_FPGA_FLASH_ADDR = FLASH_REGION_MFG_INFO_BEGIN + 0x10000; const uint32_t HEADER_SIZE = 4; // sizeof(BootFPGAHeader) uint8_t fpga_buffer[HEADER_SIZE + sizeof(s_boot_fpga)]; flash_read_bytes(fpga_buffer, BOOT_FPGA_FLASH_ADDR, sizeof(fpga_buffer)); for (int i = 0; i < sizeof(s_boot_fpga); ++i) { cl_assert(fpga_buffer[i] == 0xff); } // Write some data in mfg_info_set_rtc_freq(1); // The first time we write something into mfg_info we'll actually write the boot fpga as a side // effect. Make sure it's there. flash_read_bytes(fpga_buffer, BOOT_FPGA_FLASH_ADDR, sizeof(fpga_buffer)); cl_assert(memcmp(fpga_buffer + HEADER_SIZE, s_boot_fpga, sizeof(s_boot_fpga)) == 0); mfg_info_set_disp_offsets((GPoint) { 2, 3 }); char model[MFG_INFO_MODEL_STRING_LENGTH] = "123456789012345"; mfg_info_set_model(model); // Now let's write in an fpga image mfg_info_update_constant_data(); // Let's make sure the mfg data is still persisted cl_assert_equal_i(mfg_info_get_rtc_freq(), 1); cl_assert_equal_i(mfg_info_get_disp_offsets().x, 2); cl_assert_equal_i(mfg_info_get_disp_offsets().y, 3); char result_model[MFG_INFO_MODEL_STRING_LENGTH]; mfg_info_get_model(result_model); cl_assert_equal_s(model, result_model); // Make sure the boot fpga is still correct flash_read_bytes(fpga_buffer, BOOT_FPGA_FLASH_ADDR, sizeof(fpga_buffer)); cl_assert(memcmp(fpga_buffer + HEADER_SIZE, s_boot_fpga, sizeof(s_boot_fpga)) == 0); // Now invalidate the section and write it back. Make sure it comes back flash_write_bytes((const uint8_t*) "xxxx", BOOT_FPGA_FLASH_ADDR + HEADER_SIZE, 4); // Make sure it's corrupted flash_read_bytes(fpga_buffer, BOOT_FPGA_FLASH_ADDR, sizeof(fpga_buffer)); cl_assert(memcmp(fpga_buffer + HEADER_SIZE, s_boot_fpga, sizeof(s_boot_fpga)) != 0); // Now update it and make sure we healed the corruption mfg_info_update_constant_data(); flash_read_bytes(fpga_buffer, BOOT_FPGA_FLASH_ADDR, sizeof(fpga_buffer)); cl_assert(memcmp(fpga_buffer + HEADER_SIZE, s_boot_fpga, sizeof(s_boot_fpga)) == 0); } <|fim_middle|>mfg_info_get_watch_color()<|endoftext|>
masked_node
argument_list
src/fw/drivers/stm32f4/rtc.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "drivers/rtc.h" #include "drivers/rtc_private.h" #include "drivers/clocksource.h" #include "drivers/exti.h" #include "drivers/periph_config.h" #include "drivers/rtc.h" #include "mcu/interrupts.h" #include "system/logging.h" #include "system/passert.h" #define STM32F4_COMPATIBLE #define STM32F7_COMPATIBLE #include <mcu.h> #include "FreeRTOS.h" #include "task.h" #define LSE_FREQUENCY_HZ 32768 static uint64_t s_alarm_set_time_milliseconds_since_epoch; static const int RTC_CLOCK_ASYNC_PRESCALER = 127; static const int RTC_CLOCK_SYNC_PRESCALER = 255; void rtc_init(void) { periph_config_acquire_lock(); rtc_enable_backup_regs(); clocksource_lse_configure(); // Only initialize the RTC periphieral if it's not already enabled. if (!(RCC->BDCR & RCC_BDCR_RTCEN)) { RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE); RCC_RTCCLKCmd(ENABLE); RTC_InitTypeDef rtc_init_struct; RTC_StructInit(&rtc_init_struct); rtc_init_struct.RTC_AsynchPrediv = RTC_CLOCK_ASYNC_PRESCALER; rtc_init_struct.RTC_SynchPrediv = RTC_CLOCK_SYNC_PRESCALER; RTC_Init(&rtc_init_struct); } RTC_WaitForSynchro(); periph_config_release_lock(); #ifdef PBL_LOG_ENABLED char buffer[TIME_STRING_BUFFER_SIZE]; PBL_LOG(LOG_LEVEL_DEBUG, "Current time is <%s>", rtc_get_time_string(buffer)); #endif } void rtc_calibrate_frequency(uint32_t frequency) { // Nothing to do here! (yet) } void rtc_init_timers(void) { // Nothing to do here! } RtcTicks rtc_get_ticks(void) { static TickType_t s_last_freertos_tick_count = 0; static RtcTicks s_coarse_ticks = 0; bool ints_enabled = mcu_state_are_interrupts_enabled(); if (ints_enabled) { __disable_irq(); } TickType_t freertos_tick_count = xTaskGetTickCount(); if (freertos_tick_count < s_last_freertos_tick_count) { // We rolled over! Note this will happen every 2^32 / 1024 (tick rate) seconds, which is about // 49 days. If this function doesn't get called for 49 days we'll miss a rollover but that's // extremely unlikely. TickType_t rollover_amount = -1; s_coarse_ticks += rollover_amount; } s_last_freertos_tick_count = freertos_tick_count; RtcTicks ret_value = freertos_tick_count + s_coarse_ticks; if (ints_enabled) { __enable_irq(); } return ret_value; } void rtc_set_time(time_t time) { struct tm t; gmtime_r(&time, &t); // Just die if sanitization is necessary. PBL_ASSERTN(!rtc_sanitize_struct_tm(&t)); RTC_TimeTypeDef rtc_time_struct = { .RTC_Hours = t.tm_hour, .RTC_Minutes = t.tm_min, .RTC_Seconds = t.tm_sec }; RTC_DateTypeDef rtc_date_struct = { .RTC_Month = t.tm_mon + 1, // RTC_Month is 1-12, tm_mon is 0-11 .RTC_Date = t.tm_mday, .RTC_Year = (t.tm_year % 100) // tm_year is years since 1900, RTC_Year is just 0-99 }; RTC_SetTime
; RTC_SetDate(RTC_Format_BIN, &rtc_date_struct); } void rtc_get_time_ms(time_t* out_seconds, uint16_t* out_ms) { uint32_t sub_seconds = 0; RTC_DateTypeDef rtc_date; RTC_TimeTypeDef rtc_time; // NOTE: There is a tricky rollover situation that can occur here if the date rolls over // between when we read the date and time registers. For example: // read date: 1/1/14 (actual time 11:59:59 PM) // [date rolls over] // read time: 12:00:00 AM (actual date now 1/2/14) // At the end of this, we would think the date and time is 1/1/14 12:00:00 AM and we // would be 24 hours behind the actual date and time. // A similar issue can occur if the seconds change right after we've read the time register // and before we've read the subsecond register // To eliminate these possibilities, we read the time register both before and after // we read the date and subsecond registers and only exit this method if we are in the same // second both before and after. int max_loops = 4; // If we loop more than this many times, something is seriously wrong while (--max_loops) { RTC_TimeTypeDef rtc_time_before; RTC_GetTime(RTC_Format_BIN, &rtc_time_before); RTC_GetDate(RTC_Format_BIN, &rtc_date); // See reference manual section 26.6.11 for SSR to milliseconds conversion sub_seconds = RTC_GetSubSecond(); // Make sure neither date nor time rolled over since we read them. RTC_GetTime(RTC_Format_BIN, &rtc_time); // we need to read the DR again because reading the RTC_TR or RTC_SSR locks the shadow register // for RTC_DR and leaves it in a stale state unless we read from it again // This causes time to go backwards once a day unless we unlock it after reading from RTC_TR RTC_GetDate(RTC_Format_BIN, &rtc_date); if (rtc_time.RTC_Seconds == rtc_time_before.RTC_Seconds) { break; } } PBL_ASSERTN(max_loops > 0); struct tm current_time = { .tm_sec = rtc_time.RTC_Seconds, .tm_min = rtc_time.RTC_Minutes, .tm_hour = rtc_time.RTC_Hours, .tm_mday = rtc_date.RTC_Date, .tm_mon = rtc_date.RTC_Month - 1, // RTC_Month is 1-12, tm_mon is 0-11 .tm_year = rtc_date.RTC_Year + 100, // RTC_Year is 0-99, tm_year is years since 1900. // Assumes 2000+ year, we may guess 20th or 21st century. .tm_wday = rtc_date.RTC_WeekDay, .tm_yday = 0, .tm_isdst = 0 }; // Verify the registers have valid values. While rtc_set_time_ms above prevents us from setting // invalid values I want to be safe against other firmwares that we've upgraded from seeding // bad values in our RTC registers which could lead to a reboot loop. bool sanitization_done = rtc_sanitize_struct_tm(&current_time); // Calculate our results *out_seconds = mktime(&current_time); *out_ms = (uint16_t)( ((RTC_CLOCK_SYNC_PRESCALER - sub_seconds) * 1000) / (RTC_CLOCK_SYNC_PRESCALER + 1)); if (sanitization_done) { // Fix up the underlying registers so we don't have to do this again. rtc_set_time(*out_seconds); } } time_t rtc_get_time(void) { time_t seconds; uint16_t ms; rtc_get_time_ms(&seconds, &ms); return seconds; } //! Tracks whether we've successfully initialized the wakeup functionality static bool s_rtc_wakeup_initialized = false; static const int RTC_WAKEUP_HZ = LSE_FREQUENCY_HZ / 2; void rtc_alarm_init(void) { RTC_ITConfig(RTC_IT_WUT, DISABLE); RTC_WakeUpCmd(DISABLE); // Make sure this in in sync with the definition of LSE_FREQUENCY_HZ. This is the lowest setting // for the highest frequency and therefore the highest accurracy. However, it limits us to only // setting wakeup timers for up to 4s~ (2^16 max counter value / (32768 / 2)) in the future. // This is fine for now as we have a regular timer register each second, so we'll never want to // stop for more than a single second. RTC_WakeUpClockConfig(RTC_WakeUpClock_RTCCLK_Div2); exti_configure_other(ExtiLineOther_RTCWakeup, ExtiTrigger_Rising); exti_enable_other(ExtiLineOther_RTCWakeup);
(RTC_Format_BIN, &rtc_time_struct)
<|repo_name|>pebble <|file_sep|>src/fw/drivers/stm32f4/rtc.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "drivers/rtc.h" #include "drivers/rtc_private.h" #include "drivers/clocksource.h" #include "drivers/exti.h" #include "drivers/periph_config.h" #include "drivers/rtc.h" #include "mcu/interrupts.h" #include "system/logging.h" #include "system/passert.h" #define STM32F4_COMPATIBLE #define STM32F7_COMPATIBLE #include <mcu.h> #include "FreeRTOS.h" #include "task.h" #define LSE_FREQUENCY_HZ 32768 static uint64_t s_alarm_set_time_milliseconds_since_epoch; static const int RTC_CLOCK_ASYNC_PRESCALER = 127; static const int RTC_CLOCK_SYNC_PRESCALER = 255; void rtc_init(void) { periph_config_acquire_lock(); rtc_enable_backup_regs(); clocksource_lse_configure(); // Only initialize the RTC periphieral if it's not already enabled. if (!(RCC->BDCR & RCC_BDCR_RTCEN)) { RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE); RCC_RTCCLKCmd(ENABLE); RTC_InitTypeDef rtc_init_struct; RTC_StructInit(&rtc_init_struct); rtc_init_struct.RTC_AsynchPrediv = RTC_CLOCK_ASYNC_PRESCALER; rtc_init_struct.RTC_SynchPrediv = RTC_CLOCK_SYNC_PRESCALER; RTC_Init(&rtc_init_struct); } RTC_WaitForSynchro(); periph_config_release_lock(); #ifdef PBL_LOG_ENABLED char buffer[TIME_STRING_BUFFER_SIZE]; PBL_LOG(LOG_LEVEL_DEBUG, "Current time is <%s>", rtc_get_time_string(buffer)); #endif } void rtc_calibrate_frequency(uint32_t frequency) { // Nothing to do here! (yet) } void rtc_init_timers(void) { // Nothing to do here! } RtcTicks rtc_get_ticks(void) { static TickType_t s_last_freertos_tick_count = 0; static RtcTicks s_coarse_ticks = 0; bool ints_enabled = mcu_state_are_interrupts_enabled(); if (ints_enabled) { __disable_irq(); } TickType_t freertos_tick_count = xTaskGetTickCount(); if (freertos_tick_count < s_last_freertos_tick_count) { // We rolled over! Note this will happen every 2^32 / 1024 (tick rate) seconds, which is about // 49 days. If this function doesn't get called for 49 days we'll miss a rollover but that's // extremely unlikely. TickType_t rollover_amount = -1; s_coarse_ticks += rollover_amount; } s_last_freertos_tick_count = freertos_tick_count; RtcTicks ret_value = freertos_tick_count + s_coarse_ticks; if (ints_enabled) { __enable_irq(); } return ret_value; } void rtc_set_time(time_t time) { struct tm t; gmtime_r(&time, &t); // Just die if sanitization is necessary. PBL_ASSERTN(!rtc_sanitize_struct_tm(&t)); RTC_TimeTypeDef rtc_time_struct = { .RTC_Hours = t.tm_hour, .RTC_Minutes = t.tm_min, .RTC_Seconds = t.tm_sec }; RTC_DateTypeDef rtc_date_struct = { .RTC_Month = t.tm_mon + 1, // RTC_Month is 1-12, tm_mon is 0-11 .RTC_Date = t.tm_mday, .RTC_Year = (t.tm_year % 100) // tm_year is years since 1900, RTC_Year is just 0-99 }; RTC_SetTime<|fim_suffix|>; RTC_SetDate(RTC_Format_BIN, &rtc_date_struct); } void rtc_get_time_ms(time_t* out_seconds, uint16_t* out_ms) { uint32_t sub_seconds = 0; RTC_DateTypeDef rtc_date; RTC_TimeTypeDef rtc_time; // NOTE: There is a tricky rollover situation that can occur here if the date rolls over // between when we read the date and time registers. For example: // read date: 1/1/14 (actual time 11:59:59 PM) // [date rolls over] // read time: 12:00:00 AM (actual date now 1/2/14) // At the end of this, we would think the date and time is 1/1/14 12:00:00 AM and we // would be 24 hours behind the actual date and time. // A similar issue can occur if the seconds change right after we've read the time register // and before we've read the subsecond register // To eliminate these possibilities, we read the time register both before and after // we read the date and subsecond registers and only exit this method if we are in the same // second both before and after. int max_loops = 4; // If we loop more than this many times, something is seriously wrong while (--max_loops) { RTC_TimeTypeDef rtc_time_before; RTC_GetTime(RTC_Format_BIN, &rtc_time_before); RTC_GetDate(RTC_Format_BIN, &rtc_date); // See reference manual section 26.6.11 for SSR to milliseconds conversion sub_seconds = RTC_GetSubSecond(); // Make sure neither date nor time rolled over since we read them. RTC_GetTime(RTC_Format_BIN, &rtc_time); // we need to read the DR again because reading the RTC_TR or RTC_SSR locks the shadow register // for RTC_DR and leaves it in a stale state unless we read from it again // This causes time to go backwards once a day unless we unlock it after reading from RTC_TR RTC_GetDate(RTC_Format_BIN, &rtc_date); if (rtc_time.RTC_Seconds == rtc_time_before.RTC_Seconds) { break; } } PBL_ASSERTN(max_loops > 0); struct tm current_time = { .tm_sec = rtc_time.RTC_Seconds, .tm_min = rtc_time.RTC_Minutes, .tm_hour = rtc_time.RTC_Hours, .tm_mday = rtc_date.RTC_Date, .tm_mon = rtc_date.RTC_Month - 1, // RTC_Month is 1-12, tm_mon is 0-11 .tm_year = rtc_date.RTC_Year + 100, // RTC_Year is 0-99, tm_year is years since 1900. // Assumes 2000+ year, we may guess 20th or 21st century. .tm_wday = rtc_date.RTC_WeekDay, .tm_yday = 0, .tm_isdst = 0 }; // Verify the registers have valid values. While rtc_set_time_ms above prevents us from setting // invalid values I want to be safe against other firmwares that we've upgraded from seeding // bad values in our RTC registers which could lead to a reboot loop. bool sanitization_done = rtc_sanitize_struct_tm(&current_time); // Calculate our results *out_seconds = mktime(&current_time); *out_ms = (uint16_t)( ((RTC_CLOCK_SYNC_PRESCALER - sub_seconds) * 1000) / (RTC_CLOCK_SYNC_PRESCALER + 1)); if (sanitization_done) { // Fix up the underlying registers so we don't have to do this again. rtc_set_time(*out_seconds); } } time_t rtc_get_time(void) { time_t seconds; uint16_t ms; rtc_get_time_ms(&seconds, &ms); return seconds; } //! Tracks whether we've successfully initialized the wakeup functionality static bool s_rtc_wakeup_initialized = false; static const int RTC_WAKEUP_HZ = LSE_FREQUENCY_HZ / 2; void rtc_alarm_init(void) { RTC_ITConfig(RTC_IT_WUT, DISABLE); RTC_WakeUpCmd(DISABLE); // Make sure this in in sync with the definition of LSE_FREQUENCY_HZ. This is the lowest setting // for the highest frequency and therefore the highest accurracy. However, it limits us to only // setting wakeup timers for up to 4s~ (2^16 max counter value / (32768 / 2)) in the future. // This is fine for now as we have a regular timer register each second, so we'll never want to // stop for more than a single second. RTC_WakeUpClockConfig(RTC_WakeUpClock_RTCCLK_Div2); exti_configure_other(ExtiLineOther_RTCWakeup, ExtiTrigger_Rising); exti_enable_other(ExtiLineOther_RTCWakeup); <|fim_middle|>(RTC_Format_BIN, &rtc_time_struct)<|endoftext|>
masked_node
call_expression
src/fw/services/common/battery/battery_monitor.c
) { power_states[next_state].enter(); } } static void prv_enter_lpm(void) { #ifndef BATTERY_DEBUG if (!firmware_update_is_in_progress()) { low_power_enter(); } #endif PBL_LOG_COLOR(LOG_LEVEL_INFO, BATT_LOG_COLOR, "Battery low: enter low power mode"); } static void prv_resume_normal_operation(void) { low_power_exit(); PBL_LOG_COLOR(LOG_LEVEL_INFO, BATT_LOG_COLOR, "Battery good: resume normal operation"); } static void prv_exit_critical(void) { // Checking the state here is a bit of a hack because the state machine does not have proper // transition actions, only entry/exit actions. // We check that the state is PowerStateGood because the state machine does not transition through // all states in between the new and old states in a transition. if (s_power_state == PowerStateGood) { prv_resume_normal_operation(); } } static void prv_exit_lpm(void) { // Checking the state here is a bit of a hack because the state machine does not have proper // transition actions, only entry/exit actions if (s_power_state == PowerStateGood) { prv_resume_normal_operation(); } } static void prv_standby_timer_callback(void* data) { // FIXME This is so broken: battery_state_force_update schedules a new timer callback to execute // immediately, which then pends a background task callback to perform the update, so this will // never update before we check the power_state. battery_state_force_update(); if (s_power_state == PowerStateCritical) { // Still critical after timeout, transition to standby prv_transition(PowerStateStandby); } } static void prv_begin_standby_timer(void) { PBL_LOG_COLOR(LOG_LEVEL_INFO, BATT_LOG_COLOR, "Battery critical: begin standby timer"); // If the watch was already running, give them 30s, otherwise just 2s. uint32_t standby_timeout = (s_first_run) ? 2000: 30000; new_timer_start(s_standby_timer_id, standby_timeout, prv_standby_timer_callback, NULL, 0 /*flags*/); } static void system_task_handle_battery_critical(void* data) { PBL_LOG_COLOR(LOG_LEVEL_INFO, BATT_LOG_COLOR, "Battery critical: go to standby mode"); if (low_power_is_active()) { low_power_standby(); } else { enter_standby(RebootReasonCode_LowBattery); } } static void prv_enter_standby(void) { system_task_add_callback(system_task_handle_battery_critical, NULL); } static void prv_log_battery_state(PreciseBatteryChargeState state) { const uint16_t k_min_percent_diff = 5; const uint16_t percent = ratio32_to_percent(state.charge_percent); union LoggingBattState{ struct { uint16_t is_charging:1; uint16_t is_plugged:1; uint16_t percent:14; }; uint16_t all; }; static union LoggingBattState s_prev_batt_state; union LoggingBattState new_batt_state = { .percent = percent / k_min_percent_diff, .is_charging = state.is_charging, .is_plugged = state.is_plugged, }; if ((percent < BOARD_CONFIG_POWER.low_power_threshold) || (s_prev_batt_state.all != new_batt_state.all) || s_first_run) { s_prev_batt_state.all = new_batt_state.all; PBL_LOG_COLOR(LOG_LEVEL_INFO, BATT_LOG_COLOR, "Percent: %d Charging: %d Plugged: %d", percent, state.is_charging, state.is_plugged); } } void battery_monitor_handle_state_change_event(PreciseBatteryChargeState state) { // Update Critical/Low Power Mode // Standby behaviour, as gleaned from the previous implementation: // Once the battery voltage falls below exactly 0%, the standby lockout is displayed. // If the USB cable is disconnected, the standby timer starts. This standby delay is 2s // (if at first start), otherwise it is 30s (if the watch was already running). // The shutdown can be averted if the watch is plugged in before the timer expires. // Similarly, if the battery voltage has rebounded when the timer expires, the shutdown // will not occur. bool critical = (state.charge_percent == 0) && !state.is_charging; #ifndef RECOVERY_FW const uint32_t LOW_POWER_PERCENT =
; bool low_power = !state.is_charging && (state.charge_percent <= LOW_POWER_PERCENT); s_low_on_first_run = s_low_on_first_run || (low_power && s_first_run); #else const uint32_t PRF_LOW_POWER_THRESHOLD_PERCENT = ratio32_from_percent(5); // We want to keep the LPM UI up until we've hit 10% regardless of charging bool low_power = state.charge_percent < PRF_LOW_POWER_THRESHOLD_PERCENT; s_low_on_first_run = false; #endif PowerStateID new_state; if (critical || s_low_on_first_run) { new_state = PowerStateCritical; } else if (low_power) { new_state = PowerStateLowPower; } else { new_state = PowerStateGood; } // All state transitions are valid in this state machine. prv_transition(new_state); prv_log_battery_state(state); s_first_run = false; } void battery_monitor_init(void) { s_standby_timer_id = new_timer_create(); s_power_state = PowerStateGood; s_low_on_first_run = false; s_first_run = true; // Initialize driver interface battery_state_init(); } bool battery_monitor_critical_lockout(void) { // critical or low on first run return s_power_state == PowerStateCritical; } TimerID battery_monitor_get_standby_timer_id(void) { return s_standby_timer_id; }
ratio32_from_percent(BOARD_CONFIG_POWER.low_power_threshold)
<|repo_name|>pebble <|file_sep|>src/fw/services/common/battery/battery_monitor.c <|fim_prefix|>) { power_states[next_state].enter(); } } static void prv_enter_lpm(void) { #ifndef BATTERY_DEBUG if (!firmware_update_is_in_progress()) { low_power_enter(); } #endif PBL_LOG_COLOR(LOG_LEVEL_INFO, BATT_LOG_COLOR, "Battery low: enter low power mode"); } static void prv_resume_normal_operation(void) { low_power_exit(); PBL_LOG_COLOR(LOG_LEVEL_INFO, BATT_LOG_COLOR, "Battery good: resume normal operation"); } static void prv_exit_critical(void) { // Checking the state here is a bit of a hack because the state machine does not have proper // transition actions, only entry/exit actions. // We check that the state is PowerStateGood because the state machine does not transition through // all states in between the new and old states in a transition. if (s_power_state == PowerStateGood) { prv_resume_normal_operation(); } } static void prv_exit_lpm(void) { // Checking the state here is a bit of a hack because the state machine does not have proper // transition actions, only entry/exit actions if (s_power_state == PowerStateGood) { prv_resume_normal_operation(); } } static void prv_standby_timer_callback(void* data) { // FIXME This is so broken: battery_state_force_update schedules a new timer callback to execute // immediately, which then pends a background task callback to perform the update, so this will // never update before we check the power_state. battery_state_force_update(); if (s_power_state == PowerStateCritical) { // Still critical after timeout, transition to standby prv_transition(PowerStateStandby); } } static void prv_begin_standby_timer(void) { PBL_LOG_COLOR(LOG_LEVEL_INFO, BATT_LOG_COLOR, "Battery critical: begin standby timer"); // If the watch was already running, give them 30s, otherwise just 2s. uint32_t standby_timeout = (s_first_run) ? 2000: 30000; new_timer_start(s_standby_timer_id, standby_timeout, prv_standby_timer_callback, NULL, 0 /*flags*/); } static void system_task_handle_battery_critical(void* data) { PBL_LOG_COLOR(LOG_LEVEL_INFO, BATT_LOG_COLOR, "Battery critical: go to standby mode"); if (low_power_is_active()) { low_power_standby(); } else { enter_standby(RebootReasonCode_LowBattery); } } static void prv_enter_standby(void) { system_task_add_callback(system_task_handle_battery_critical, NULL); } static void prv_log_battery_state(PreciseBatteryChargeState state) { const uint16_t k_min_percent_diff = 5; const uint16_t percent = ratio32_to_percent(state.charge_percent); union LoggingBattState{ struct { uint16_t is_charging:1; uint16_t is_plugged:1; uint16_t percent:14; }; uint16_t all; }; static union LoggingBattState s_prev_batt_state; union LoggingBattState new_batt_state = { .percent = percent / k_min_percent_diff, .is_charging = state.is_charging, .is_plugged = state.is_plugged, }; if ((percent < BOARD_CONFIG_POWER.low_power_threshold) || (s_prev_batt_state.all != new_batt_state.all) || s_first_run) { s_prev_batt_state.all = new_batt_state.all; PBL_LOG_COLOR(LOG_LEVEL_INFO, BATT_LOG_COLOR, "Percent: %d Charging: %d Plugged: %d", percent, state.is_charging, state.is_plugged); } } void battery_monitor_handle_state_change_event(PreciseBatteryChargeState state) { // Update Critical/Low Power Mode // Standby behaviour, as gleaned from the previous implementation: // Once the battery voltage falls below exactly 0%, the standby lockout is displayed. // If the USB cable is disconnected, the standby timer starts. This standby delay is 2s // (if at first start), otherwise it is 30s (if the watch was already running). // The shutdown can be averted if the watch is plugged in before the timer expires. // Similarly, if the battery voltage has rebounded when the timer expires, the shutdown // will not occur. bool critical = (state.charge_percent == 0) && !state.is_charging; #ifndef RECOVERY_FW const uint32_t LOW_POWER_PERCENT = <|fim_suffix|>; bool low_power = !state.is_charging && (state.charge_percent <= LOW_POWER_PERCENT); s_low_on_first_run = s_low_on_first_run || (low_power && s_first_run); #else const uint32_t PRF_LOW_POWER_THRESHOLD_PERCENT = ratio32_from_percent(5); // We want to keep the LPM UI up until we've hit 10% regardless of charging bool low_power = state.charge_percent < PRF_LOW_POWER_THRESHOLD_PERCENT; s_low_on_first_run = false; #endif PowerStateID new_state; if (critical || s_low_on_first_run) { new_state = PowerStateCritical; } else if (low_power) { new_state = PowerStateLowPower; } else { new_state = PowerStateGood; } // All state transitions are valid in this state machine. prv_transition(new_state); prv_log_battery_state(state); s_first_run = false; } void battery_monitor_init(void) { s_standby_timer_id = new_timer_create(); s_power_state = PowerStateGood; s_low_on_first_run = false; s_first_run = true; // Initialize driver interface battery_state_init(); } bool battery_monitor_critical_lockout(void) { // critical or low on first run return s_power_state == PowerStateCritical; } TimerID battery_monitor_get_standby_timer_id(void) { return s_standby_timer_id; } <|fim_middle|>ratio32_from_percent(BOARD_CONFIG_POWER.low_power_threshold)<|endoftext|>
prefix_only
compound_statement
src/fw/syscall/ble_syscalls.c
out)); syscall_assert_userspace_buffer(value_out, *value_length_in_out); syscall_assert_userspace_buffer(has_more_out, sizeof(*has_more_out)); } return gatt_client_subscriptions_consume_notification(object_ref_out, value_out, value_length_in_out, GAPLEClientApp, has_more_out); } DEFINE_SYSCALL(BTErrno, sys_ble_client_write, BLECharacteristic characteristic, const uint8_t *value, size_t value_length) { return gatt_client_op_write(characteristic, value, value_length, GAPLEClientApp); } DEFINE_SYSCALL(BTErrno, sys_ble_client_write_without_response, BLECharacteristic characteristic, const uint8_t *value, size_t value_length) { return gatt_client_op_write_without_response(characteristic, value, value_length, GAPLEClientApp); } DEFINE_SYSCALL(BTErrno, sys_ble_client_subscribe, BLECharacteristic characteristic, BLESubscription subscription_type) { return gatt_client_subscriptions_subscribe(characteristic, subscription_type, GAPLEClientApp); } DEFINE_SYSCALL(BTErrno, sys_ble_client_write_descriptor, BLEDescriptor descriptor, const uint8_t *value, size_t value_length) { return gatt_client_op_write_descriptor(descriptor, value, value_length, GAPLEClientApp); } DEFINE_SYSCALL(BTErrno, sys_ble_client_read_descriptor, BLEDescriptor descriptor) { return gatt_client_op_read_descriptor(descriptor, GAPLEClientApp); } // ----------------------------------------------------------------------------- // ble_service.h DEFINE_SYSCALL(uint8_t, sys_ble_service_get_characteristics, BLEService service_ref, BLECharacteristic characteristics_out[], uint8_t num_characteristics) { if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer(characteristics_out, sizeof(BLECharacteristic) * num_characteristics); } return gatt_client_service_get_characteristics(service_ref, characteristics_out, num_characteristics); } DEFINE_SYSCALL(void, sys_ble_service_get_uuid, Uuid *uuid, BLEService service_ref) { if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer(uuid, sizeof(*uuid)); } *uuid = gatt_client_service_get_uuid(service_ref); } DEFINE_SYSCALL(void, sys_ble_service_get_device, BTDeviceInternal *device, BLEService service) { if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer(device, sizeof(*device)); } *device = gatt_client_service_get_device(service); } DEFINE_SYSCALL(uint8_t, sys_ble_service_get_included_services, BLEService service_ref, BLEService included_services_out[], uint8_t num_services) { if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer(included_services_out, sizeof(BLEService) * num_services); } return gatt_client_service_get_included_services(service_ref, included_services_out, num_services); } // ----------------------------------------------------------------------------- // ble_characteristic.h DEFINE_SYSCALL(void, sys_ble_characteristic_get_uuid, Uuid *uuid, BLECharacteristic characteristic)
{ if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer(uuid, sizeof(*uuid)); } *uuid = gatt_client_characteristic_get_uuid(characteristic); }
<|repo_name|>pebble <|file_sep|>src/fw/syscall/ble_syscalls.c <|fim_prefix|>out)); syscall_assert_userspace_buffer(value_out, *value_length_in_out); syscall_assert_userspace_buffer(has_more_out, sizeof(*has_more_out)); } return gatt_client_subscriptions_consume_notification(object_ref_out, value_out, value_length_in_out, GAPLEClientApp, has_more_out); } DEFINE_SYSCALL(BTErrno, sys_ble_client_write, BLECharacteristic characteristic, const uint8_t *value, size_t value_length) { return gatt_client_op_write(characteristic, value, value_length, GAPLEClientApp); } DEFINE_SYSCALL(BTErrno, sys_ble_client_write_without_response, BLECharacteristic characteristic, const uint8_t *value, size_t value_length) { return gatt_client_op_write_without_response(characteristic, value, value_length, GAPLEClientApp); } DEFINE_SYSCALL(BTErrno, sys_ble_client_subscribe, BLECharacteristic characteristic, BLESubscription subscription_type) { return gatt_client_subscriptions_subscribe(characteristic, subscription_type, GAPLEClientApp); } DEFINE_SYSCALL(BTErrno, sys_ble_client_write_descriptor, BLEDescriptor descriptor, const uint8_t *value, size_t value_length) { return gatt_client_op_write_descriptor(descriptor, value, value_length, GAPLEClientApp); } DEFINE_SYSCALL(BTErrno, sys_ble_client_read_descriptor, BLEDescriptor descriptor) { return gatt_client_op_read_descriptor(descriptor, GAPLEClientApp); } // ----------------------------------------------------------------------------- // ble_service.h DEFINE_SYSCALL(uint8_t, sys_ble_service_get_characteristics, BLEService service_ref, BLECharacteristic characteristics_out[], uint8_t num_characteristics) { if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer(characteristics_out, sizeof(BLECharacteristic) * num_characteristics); } return gatt_client_service_get_characteristics(service_ref, characteristics_out, num_characteristics); } DEFINE_SYSCALL(void, sys_ble_service_get_uuid, Uuid *uuid, BLEService service_ref) { if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer(uuid, sizeof(*uuid)); } *uuid = gatt_client_service_get_uuid(service_ref); } DEFINE_SYSCALL(void, sys_ble_service_get_device, BTDeviceInternal *device, BLEService service) { if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer(device, sizeof(*device)); } *device = gatt_client_service_get_device(service); } DEFINE_SYSCALL(uint8_t, sys_ble_service_get_included_services, BLEService service_ref, BLEService included_services_out[], uint8_t num_services) { if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer(included_services_out, sizeof(BLEService) * num_services); } return gatt_client_service_get_included_services(service_ref, included_services_out, num_services); } // ----------------------------------------------------------------------------- // ble_characteristic.h DEFINE_SYSCALL(void, sys_ble_characteristic_get_uuid, Uuid *uuid, BLECharacteristic characteristic) <|fim_suffix|><|fim_middle|>{ if (PRIVILEGE_WAS_ELEVATED) { syscall_assert_userspace_buffer(uuid, sizeof(*uuid)); } *uuid = gatt_client_characteristic_get_uuid(characteristic); }<|endoftext|>
masked_node
argument_list
tests/fw/apps/system_apps/health/test_health_activity_summary_card.c
, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 50}, // 1000 .current_step_average = 379, }; prv_create_card_and_render(&health_data); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_health_activity_summary_card__render_current_above_typical3(void) { HealthData health_data = { .step_data = 780, .step_averages = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 50}, // 1000 .current_step_average = 480, }; prv_create_card_and_render(&health_data); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_health_activity_summary_card__render_current_above_typical4(void) { HealthData health_data = { .step_data = 866, .step_averages = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 50}, // 1000 .current_step_average = 700, }; prv_create_card_and_render(&health_data); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_health_activity_summary_card__render_current_above_typical5(void) { HealthData health_data = { .step_data = 970, .step_averages = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 50}, // 1000 .current_step_average = 900, }; prv_create_card_and_render(&health_data); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_health_activity_summary_card__render_current_above_expected(void) { HealthData health_data = { .step_data = {2000}, .step_averages = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 50}, // 1000 .current_step_average = 800, }; prv_create_card_and_render(&health_data); cl_check(gbitmap_pbi_eq
); }
(&s_ctx.dest_bitmap, TEST_PBI_FILE)
<|repo_name|>pebble <|file_sep|>tests/fw/apps/system_apps/health/test_health_activity_summary_card.c <|fim_prefix|>, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 50}, // 1000 .current_step_average = 379, }; prv_create_card_and_render(&health_data); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_health_activity_summary_card__render_current_above_typical3(void) { HealthData health_data = { .step_data = 780, .step_averages = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 50}, // 1000 .current_step_average = 480, }; prv_create_card_and_render(&health_data); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_health_activity_summary_card__render_current_above_typical4(void) { HealthData health_data = { .step_data = 866, .step_averages = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 50}, // 1000 .current_step_average = 700, }; prv_create_card_and_render(&health_data); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_health_activity_summary_card__render_current_above_typical5(void) { HealthData health_data = { .step_data = 970, .step_averages = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 50}, // 1000 .current_step_average = 900, }; prv_create_card_and_render(&health_data); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_health_activity_summary_card__render_current_above_expected(void) { HealthData health_data = { .step_data = {2000}, .step_averages = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 50}, // 1000 .current_step_average = 800, }; prv_create_card_and_render(&health_data); cl_check(gbitmap_pbi_eq<|fim_suffix|>); } <|fim_middle|>(&s_ctx.dest_bitmap, TEST_PBI_FILE)<|endoftext|>
masked_node
call_expression
src/fw/popups/bluetooth_pairing_ui.c
ch translated language twice we must show 15 total strings. // The Bluetooth SPP popup will timeout in 30 seconds so each animation + delay = 30/15 = 2s const int animation_duration_ms = 300; const int animation_delay_ms = 1700; // This is the text that is currently not visible and animates into view data->info_text_in_animation = property_animation_create_layer_frame(&data->info_text_layer2.layer, &above_pair_text, &pair_text_area); PBL_ASSERTN(data->info_text_in_animation); Animation *animation = property_animation_get_animation(data->info_text_in_animation); animation_set_auto_destroy(animation, false); animation_set_duration(animation, animation_duration_ms); animation_set_delay(animation, animation_delay_ms); // This is the text that is currently visible and animates out of view data->info_text_out_animation = property_animation_create_layer_frame(&data->info_text_layer.layer, &pair_text_area, &below_pair_text); PBL_ASSERTN(data->info_text_out_animation); animation = property_animation_get_animation(data->info_text_out_animation); animation_set_auto_destroy(animation, false); animation_set_duration(animation, animation_duration_ms); animation_set_delay(animation, animation_delay_ms); // We only need a stop handler for one of the animations as they should finish at the same time AnimationHandlers handlers = { .stopped = prv_info_text_animation_stopped, }; animation_set_handlers(animation, handlers, NULL); } static void prv_initialize_info_text(BTPairingUIData *data) { prv_animate_info_text(data); } static void prv_deinitialize_info_text(BTPairingUIData *data) { } #else // Normal FW -- use i18n text for "Pair?" static void prv_cleanup_prf_animations(BTPairingUIData *data) { } static void prv_add_prf_layers(GRect pair_text_area, BTPairingUIData *data) { } static void prv_initialize_info_text(BTPairingUIData *data) { strncpy(data->info_text_layer_buffer, (char *)i18n_get("Pair?", data), MAX_PAIR_STR_LEN); } static void prv_deinitialize_info_text(BTPairingUIData *data) { i18n_free_all(data); } #endif static uint32_t prv_resource_id_for_state(BTPairingUIState state) { switch (state) { case BTPairingUIStateAwaitingUserConfirmation: return RESOURCE_ID_BT_PAIR_CONFIRMATION; case BTPairingUIStateAwaitingResult: return RESOURCE_ID_BT_PAIR_APPROVE_ON_PHONE; case BTPairingUIStateSuccess: return RESOURCE_ID_BT_PAIR_SUCCESS; case BTPairingUIStateFailed: return RESOURCE_ID_BT_PAIR_FAILURE; default: WTF; } } static void prv_adjust_background_frame_for_state(BTPairingUIData *data) { GAlign alignment; const int16_t width_of_sidebar = data->action_bar_layer.layer.frame.size.w; const int16_t window_width = data->window.layer.bounds.size.w; const int16_t config_width = window_width - width_of_sidebar + 10; int16_t x_offset, y_offset, width; switch (data->ui_state) { case BTPairingUIStateAwaitingUserConfirmation: alignment = GAlignTopLeft; #if PLATFORM_ROBERT || PLATFORM_CALCULUS x_offset = 39; y_offset = 85; #else x_offset = PBL_IF_RECT_ELSE(10, 31); y_offset = PBL_IF_RECT_ELSE(44, 46); #endif width = config_width; break; case BTPairingUIStateAwaitingResult: alignment = GAlignLeft; #if PLATFORM_ROBERT || PLATFORM_CALCULUS x_offset = 76; y_offset = 30; #else x_offset = PBL_IF_RECT_ELSE(49, 67); y_offset = PBL_IF_RECT_ELSE(22, 25); #endif width = window_width; break; case BTPairingUIStateFailed: case BTPairingUIStateSuccess: alignment = GAlignTop; #if PLATFORM_ROBERT || PLATFORM_CALCULUS x_offset = 0; y_offset = 59; #else x_offset = 2; y_offset = PBL_IF_RECT_ELSE(30, 36); #endif width = window_width; break; default: WTF; } GRect kino_area; kino_area = GRect(x_offset, y_offset, width, data->window.layer.bounds.size.h);
; layer_set_frame(&data->kino_layer.layer, &kino_area); kino_layer_set_reel_with_resource(&data->kino_layer, prv_resource_id_for_state(data->ui_state)); } static void prv_send_response(bool is_confirmed) { if (!s_data_ptr) { return; } bt_lock(); bt_driver_pairing_confirm(s_data_ptr->ctx, is_confirmed); bt_unlock(); } static bool prv_has_device_name(BTPairingUIData *data) { return (strlen(data->device_name_layer_buffer) != 0); } static bool prv_has_confirmation_token(BTPairingUIData *data) { return (strlen(data->code_text_layer_buffer) != 0); } static void prv_exit_awaiting_user_confirmation(BTPairingUIData *data) { // Remove UI components that are not needed any more after the user input confirmation screen: prv_cleanup_prf_animations(data); layer_set_hidden(&data->info_text_layer.layer, true); if (prv_has_device_name(data)) { layer_remove_from_parent(&data->device_name_text_layer.layer); } if (prv_has_confirmation_token(data)) { layer_remove_from_parent(&data->code_text_layer.layer); } // Disable all buttons in this screen: action_bar_layer_remove_from_window(&data->action_bar_layer); action_bar_layer_set_click_config_provider(&data->action_bar_layer, NULL); } static void prv_confirm_click_handler(ClickRecognizerRef recognizer, void *ctx) { Window *window = (Window *) ctx; BTPairingUIData *data = window_get_user_data(window); PBL_ASSERTN(data->ui_state == BTPairingUIStateAwaitingUserConfirmation); prv_exit_awaiting_user_confirmation(data); data->ui_state = BTPairingUIStateAwaitingResult; prv_send_response(true /* is_confirmed */); prv_adjust_background_frame_for_state(data); } static void prv_decline_click_handler(ClickRecognizerRef recognizer, void *ctx) { Window *window = (Window *) ctx; BTPairingUIData *data = window_get_user_data(window); PBL_ASSERTN(data->ui_state == BTPairingUIStateAwaitingUserConfirmation); prv_send_response(false /* is_confirmed */); // Not updating ui_state, the handler is capable of dealing with transitioning from // BTPairingUIStateAwaitingUserConfirmation directly to BTPairingUIStateFailed prv_handle_pairing_complete(false /* success */); } static void prv_user_confirmation_click_config_provider(void *unused) { window_single_click_subscribe(BUTTON_ID_UP, prv_confirm_click_handler); window_single_click_subscribe(BUTTON_ID_DOWN, prv_decline_click_handler); } static void prv_window_load(Window *window) { BTPairingUIData *data = window_get_user_data(window); window_set_background_color(&data->window, PBL_IF_COLOR_ELSE(GColorLightGray, GColorWhite)); const int32_t width_of_action_bar_with_padding = ACTION_BAR_WIDTH + PBL_IF_RECT_ELSE(2, -4); const int32_t width = window->layer.bounds.size.w - width_of_action_bar_with_padding; const int32_t x_offset = PBL_IF_RECT_ELSE(0, 22); #if PLATFORM_ROBERT || PLATFORM_CALCULUS const int32_t info_text_y_offset = 36; #else const int32_t info_text_y_offset = PBL_IF_RECT_ELSE(10, 12); #endif KinoLayer *kino_layer = &data->kino_layer; kino_layer_init(kino_layer, &window->layer.bounds); layer_add_child(&window->layer, &kino_layer->layer); #if PLATFORM_ROBERT || PLATFORM_CALCULUS GRect pair_text_area = GRect(0, -2, width, 44); #else GRect pair_text_area = GRect(0, -2, width, 30); #endif #if PLATFORM_ROBERT || PLATFORM_CALCULUS layer_set_frame(&data->info_text_mask_layer, &GRect(x_offset, info_text_y_offset, width, 30)); #else layer_set_frame(&data->info_text_mask_layer, &GRect(x_offset, info_text_y_offset, width, 26)); #endif layer_set_clips(&data->info_text_mask_layer, true); layer_add_child(&window->layer, &data->info_text_mask_layer); TextLayer *info_text_layer = &data->info_text_layer; text_layer_init_with_parameters(info_text_layer, &pair_text_area, data->info_text_layer_buffer, #if PLATFORM_ROBERT || PLATFORM_CALCULUS fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD), #else
kino_layer_set_alignment(&data->kino_layer, alignment)
<|repo_name|>pebble <|file_sep|>src/fw/popups/bluetooth_pairing_ui.c <|fim_prefix|>ch translated language twice we must show 15 total strings. // The Bluetooth SPP popup will timeout in 30 seconds so each animation + delay = 30/15 = 2s const int animation_duration_ms = 300; const int animation_delay_ms = 1700; // This is the text that is currently not visible and animates into view data->info_text_in_animation = property_animation_create_layer_frame(&data->info_text_layer2.layer, &above_pair_text, &pair_text_area); PBL_ASSERTN(data->info_text_in_animation); Animation *animation = property_animation_get_animation(data->info_text_in_animation); animation_set_auto_destroy(animation, false); animation_set_duration(animation, animation_duration_ms); animation_set_delay(animation, animation_delay_ms); // This is the text that is currently visible and animates out of view data->info_text_out_animation = property_animation_create_layer_frame(&data->info_text_layer.layer, &pair_text_area, &below_pair_text); PBL_ASSERTN(data->info_text_out_animation); animation = property_animation_get_animation(data->info_text_out_animation); animation_set_auto_destroy(animation, false); animation_set_duration(animation, animation_duration_ms); animation_set_delay(animation, animation_delay_ms); // We only need a stop handler for one of the animations as they should finish at the same time AnimationHandlers handlers = { .stopped = prv_info_text_animation_stopped, }; animation_set_handlers(animation, handlers, NULL); } static void prv_initialize_info_text(BTPairingUIData *data) { prv_animate_info_text(data); } static void prv_deinitialize_info_text(BTPairingUIData *data) { } #else // Normal FW -- use i18n text for "Pair?" static void prv_cleanup_prf_animations(BTPairingUIData *data) { } static void prv_add_prf_layers(GRect pair_text_area, BTPairingUIData *data) { } static void prv_initialize_info_text(BTPairingUIData *data) { strncpy(data->info_text_layer_buffer, (char *)i18n_get("Pair?", data), MAX_PAIR_STR_LEN); } static void prv_deinitialize_info_text(BTPairingUIData *data) { i18n_free_all(data); } #endif static uint32_t prv_resource_id_for_state(BTPairingUIState state) { switch (state) { case BTPairingUIStateAwaitingUserConfirmation: return RESOURCE_ID_BT_PAIR_CONFIRMATION; case BTPairingUIStateAwaitingResult: return RESOURCE_ID_BT_PAIR_APPROVE_ON_PHONE; case BTPairingUIStateSuccess: return RESOURCE_ID_BT_PAIR_SUCCESS; case BTPairingUIStateFailed: return RESOURCE_ID_BT_PAIR_FAILURE; default: WTF; } } static void prv_adjust_background_frame_for_state(BTPairingUIData *data) { GAlign alignment; const int16_t width_of_sidebar = data->action_bar_layer.layer.frame.size.w; const int16_t window_width = data->window.layer.bounds.size.w; const int16_t config_width = window_width - width_of_sidebar + 10; int16_t x_offset, y_offset, width; switch (data->ui_state) { case BTPairingUIStateAwaitingUserConfirmation: alignment = GAlignTopLeft; #if PLATFORM_ROBERT || PLATFORM_CALCULUS x_offset = 39; y_offset = 85; #else x_offset = PBL_IF_RECT_ELSE(10, 31); y_offset = PBL_IF_RECT_ELSE(44, 46); #endif width = config_width; break; case BTPairingUIStateAwaitingResult: alignment = GAlignLeft; #if PLATFORM_ROBERT || PLATFORM_CALCULUS x_offset = 76; y_offset = 30; #else x_offset = PBL_IF_RECT_ELSE(49, 67); y_offset = PBL_IF_RECT_ELSE(22, 25); #endif width = window_width; break; case BTPairingUIStateFailed: case BTPairingUIStateSuccess: alignment = GAlignTop; #if PLATFORM_ROBERT || PLATFORM_CALCULUS x_offset = 0; y_offset = 59; #else x_offset = 2; y_offset = PBL_IF_RECT_ELSE(30, 36); #endif width = window_width; break; default: WTF; } GRect kino_area; kino_area = GRect(x_offset, y_offset, width, data->window.layer.bounds.size.h); <|fim_suffix|>; layer_set_frame(&data->kino_layer.layer, &kino_area); kino_layer_set_reel_with_resource(&data->kino_layer, prv_resource_id_for_state(data->ui_state)); } static void prv_send_response(bool is_confirmed) { if (!s_data_ptr) { return; } bt_lock(); bt_driver_pairing_confirm(s_data_ptr->ctx, is_confirmed); bt_unlock(); } static bool prv_has_device_name(BTPairingUIData *data) { return (strlen(data->device_name_layer_buffer) != 0); } static bool prv_has_confirmation_token(BTPairingUIData *data) { return (strlen(data->code_text_layer_buffer) != 0); } static void prv_exit_awaiting_user_confirmation(BTPairingUIData *data) { // Remove UI components that are not needed any more after the user input confirmation screen: prv_cleanup_prf_animations(data); layer_set_hidden(&data->info_text_layer.layer, true); if (prv_has_device_name(data)) { layer_remove_from_parent(&data->device_name_text_layer.layer); } if (prv_has_confirmation_token(data)) { layer_remove_from_parent(&data->code_text_layer.layer); } // Disable all buttons in this screen: action_bar_layer_remove_from_window(&data->action_bar_layer); action_bar_layer_set_click_config_provider(&data->action_bar_layer, NULL); } static void prv_confirm_click_handler(ClickRecognizerRef recognizer, void *ctx) { Window *window = (Window *) ctx; BTPairingUIData *data = window_get_user_data(window); PBL_ASSERTN(data->ui_state == BTPairingUIStateAwaitingUserConfirmation); prv_exit_awaiting_user_confirmation(data); data->ui_state = BTPairingUIStateAwaitingResult; prv_send_response(true /* is_confirmed */); prv_adjust_background_frame_for_state(data); } static void prv_decline_click_handler(ClickRecognizerRef recognizer, void *ctx) { Window *window = (Window *) ctx; BTPairingUIData *data = window_get_user_data(window); PBL_ASSERTN(data->ui_state == BTPairingUIStateAwaitingUserConfirmation); prv_send_response(false /* is_confirmed */); // Not updating ui_state, the handler is capable of dealing with transitioning from // BTPairingUIStateAwaitingUserConfirmation directly to BTPairingUIStateFailed prv_handle_pairing_complete(false /* success */); } static void prv_user_confirmation_click_config_provider(void *unused) { window_single_click_subscribe(BUTTON_ID_UP, prv_confirm_click_handler); window_single_click_subscribe(BUTTON_ID_DOWN, prv_decline_click_handler); } static void prv_window_load(Window *window) { BTPairingUIData *data = window_get_user_data(window); window_set_background_color(&data->window, PBL_IF_COLOR_ELSE(GColorLightGray, GColorWhite)); const int32_t width_of_action_bar_with_padding = ACTION_BAR_WIDTH + PBL_IF_RECT_ELSE(2, -4); const int32_t width = window->layer.bounds.size.w - width_of_action_bar_with_padding; const int32_t x_offset = PBL_IF_RECT_ELSE(0, 22); #if PLATFORM_ROBERT || PLATFORM_CALCULUS const int32_t info_text_y_offset = 36; #else const int32_t info_text_y_offset = PBL_IF_RECT_ELSE(10, 12); #endif KinoLayer *kino_layer = &data->kino_layer; kino_layer_init(kino_layer, &window->layer.bounds); layer_add_child(&window->layer, &kino_layer->layer); #if PLATFORM_ROBERT || PLATFORM_CALCULUS GRect pair_text_area = GRect(0, -2, width, 44); #else GRect pair_text_area = GRect(0, -2, width, 30); #endif #if PLATFORM_ROBERT || PLATFORM_CALCULUS layer_set_frame(&data->info_text_mask_layer, &GRect(x_offset, info_text_y_offset, width, 30)); #else layer_set_frame(&data->info_text_mask_layer, &GRect(x_offset, info_text_y_offset, width, 26)); #endif layer_set_clips(&data->info_text_mask_layer, true); layer_add_child(&window->layer, &data->info_text_mask_layer); TextLayer *info_text_layer = &data->info_text_layer; text_layer_init_with_parameters(info_text_layer, &pair_text_area, data->info_text_layer_buffer, #if PLATFORM_ROBERT || PLATFORM_CALCULUS fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD), #else <|fim_middle|>kino_layer_set_alignment(&data->kino_layer, alignment)<|endoftext|>
masked_node
argument_list
tests/fw/graphics/test_graphics_draw_line.c
nt(0, 18), 22); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 20), MAX_NUM_COLS - 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 22), MAX_NUM_COLS + 1); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_even_offset_even_rows_no_clip"))); // Odd rows of different lengths setup_test_aa_sw(&ctx, fb, OFFSET_RECT_EVEN, OFFSET_RECT_EVEN, false, 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 1), MAX_NUM_COLS); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 3), MAX_NUM_COLS + 4); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 5), 0); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 7), 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 9), 2); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 11), 3); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 13), 4); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 15), 20); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 17), 21); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 19), 22); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 21), MAX_NUM_COLS - 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 23), MAX_NUM_COLS + 1); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_even_offset_odd_rows_no_clip"))); // Test to make sure drawing on all rows creates checkerboard pattern setup_test_aa_sw(&ctx, fb, OFFSET_RECT_EVEN, OFFSET_RECT_EVEN, false, 1); for (int16_t row = 0; row < MAX_NUM_ROWS; row++) { graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, row), MAX_NUM_COLS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_even_offset_checkerboard_no_clip"))); // Clipping on even boundaries - no offset setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_EVEN, OFFSET_RECT_EVEN, false, 1); for (int16_t row = 0; row < MAX_NUM_ROWS; row++) { graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, row), MAX_NUM_COLS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_even_offset_even_clip"))); // Clipping on odd boundaries - no offset setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_ODD, OFFSET_RECT_EVEN, false, 1); for (int16_t row = 0; row < MAX_NUM_ROWS; row++) { graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, row), MAX_NUM_COLS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_even_offset_odd_clip"))); } void test_graphics_draw_line___odd_offset_horizontal_dotted(void) { GContext ctx; test_graphics_context_init(&ctx, fb); // Test odd and even rows draw appropriately setup_test_aa_sw(&ctx, fb, OFFSET_RECT_ODD, OFFSET_RECT_ODD, false, 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(6, 12), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(6, 23), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(7, 13), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(7, 24), 10); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_odd_offset_no_clip"))); // Even rows of different lengths setup_test_aa_sw(&ctx, fb, OFFSET_RECT_ODD, OFFSET_RECT_ODD, false, 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 0), MAX_NUM_COLS); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 2), MAX_NUM_COLS + 4); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 4), 0); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 6), 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 8), 2); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 10), 3); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 12), 4); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 14), 20); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 16), 21); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 18), 22); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 20), MAX_NUM_COLS - 1); graphics_draw_horizontal_line_dotted
; cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_odd_offset_even_rows_no_clip"))); // Odd rows of different lengths setup_test_aa_sw(&ctx, fb, OFFSET_RECT_ODD, OFFSET_RECT_ODD, false, 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 1), MAX_NUM_COLS); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 3), MAX_NUM_COLS + 4); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 5), 0); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 7), 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 9), 2); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 11), 3); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 13), 4); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 15), 20); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 17), 21); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 19), 22); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 21), MAX_NUM_COLS - 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 23), MAX_NUM_COLS + 1); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_odd_offset_odd_rows_no_clip"))); // Test to make sure drawing on all rows creates checkerboard pattern setup_test_aa_sw(&ctx, fb, OFFSET_RECT_ODD, OFFSET_RECT_ODD, false, 1); for (int16_t row = 0; row < MAX_NUM_ROWS; row++) { graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, row), MAX_NUM_COLS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_odd_offset_checkerboard_no_clip"))); // Clipping on even boundaries - no offset setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_EVEN, OFFSET_RECT_ODD, false, 1); for (int16_t row = 0; row < MAX_NUM_ROWS; row++) { graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, row), MAX_NUM_COLS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_odd_offset_even_clip"))); // Clipping on odd boundaries - no offset setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_ODD, OFFSET_RECT_ODD, false, 1); for (int16_t row = 0; row < MAX_NUM_ROWS; row++) { graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, row), MAX_NUM_COLS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_odd_offset_odd_clip"))); } void test_graphics_draw_line___origin_vertical_dotted(void) { GContext ctx; test_graphics_context_init(&ctx, fb); // Test odd and even cols draw appropriately setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(12, 6), 10); graphics_draw_vertical_line_dotted(&ctx, GPoint(23, 6), 10); graphics_draw_vertical_line_dotted(&ctx, GPoint(13, 7), 10); graphics_draw_vertical_line_dotted(&ctx, GPoint(24, 7), 10); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_origin_no_clip"))); // Even cols of different lengths setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(0, 0), MAX_NUM_ROWS); graphics_draw_vertical_line_dotted(&ctx, GPoint(2, 0), MAX_NUM_ROWS + 4); graphics_draw_vertical_line_dotted(&ctx, GPoint(4, 0), 0); graphics_draw_vertical_line_dotted(&ctx, GPoint(6, 0), 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(8, 0), 2); graphics_draw_vertical_line_dotted(&ctx, GPoint(10, 0), 3); graphics_draw_vertical_line_dotted(&ctx, GPoint(12, 0), 4); graphics_draw_vertical_line_dotted(&ctx, GPoint(14, 0), 20); graphics_draw_vertical_line_dotted(&ctx, GPoint(16, 0), 21); graphics_draw_vertical_line_dotted(&ctx, GPoint(18, 0), 22); graphics_draw_vertical_line_dotted(&ctx, GPoint(20, 0), MAX_NUM_ROWS - 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(22, 0), MAX_NUM_ROWS + 1 ); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_origin_even_cols_no_clip"))); // Odd cols of different lengths setup
(&ctx, GPoint(0, 22), MAX_NUM_COLS + 1)
<|repo_name|>pebble <|file_sep|>tests/fw/graphics/test_graphics_draw_line.c <|fim_prefix|>nt(0, 18), 22); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 20), MAX_NUM_COLS - 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 22), MAX_NUM_COLS + 1); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_even_offset_even_rows_no_clip"))); // Odd rows of different lengths setup_test_aa_sw(&ctx, fb, OFFSET_RECT_EVEN, OFFSET_RECT_EVEN, false, 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 1), MAX_NUM_COLS); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 3), MAX_NUM_COLS + 4); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 5), 0); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 7), 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 9), 2); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 11), 3); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 13), 4); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 15), 20); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 17), 21); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 19), 22); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 21), MAX_NUM_COLS - 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 23), MAX_NUM_COLS + 1); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_even_offset_odd_rows_no_clip"))); // Test to make sure drawing on all rows creates checkerboard pattern setup_test_aa_sw(&ctx, fb, OFFSET_RECT_EVEN, OFFSET_RECT_EVEN, false, 1); for (int16_t row = 0; row < MAX_NUM_ROWS; row++) { graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, row), MAX_NUM_COLS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_even_offset_checkerboard_no_clip"))); // Clipping on even boundaries - no offset setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_EVEN, OFFSET_RECT_EVEN, false, 1); for (int16_t row = 0; row < MAX_NUM_ROWS; row++) { graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, row), MAX_NUM_COLS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_even_offset_even_clip"))); // Clipping on odd boundaries - no offset setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_ODD, OFFSET_RECT_EVEN, false, 1); for (int16_t row = 0; row < MAX_NUM_ROWS; row++) { graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, row), MAX_NUM_COLS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_even_offset_odd_clip"))); } void test_graphics_draw_line___odd_offset_horizontal_dotted(void) { GContext ctx; test_graphics_context_init(&ctx, fb); // Test odd and even rows draw appropriately setup_test_aa_sw(&ctx, fb, OFFSET_RECT_ODD, OFFSET_RECT_ODD, false, 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(6, 12), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(6, 23), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(7, 13), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(7, 24), 10); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_odd_offset_no_clip"))); // Even rows of different lengths setup_test_aa_sw(&ctx, fb, OFFSET_RECT_ODD, OFFSET_RECT_ODD, false, 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 0), MAX_NUM_COLS); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 2), MAX_NUM_COLS + 4); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 4), 0); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 6), 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 8), 2); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 10), 3); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 12), 4); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 14), 20); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 16), 21); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 18), 22); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 20), MAX_NUM_COLS - 1); graphics_draw_horizontal_line_dotted<|fim_suffix|>; cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_odd_offset_even_rows_no_clip"))); // Odd rows of different lengths setup_test_aa_sw(&ctx, fb, OFFSET_RECT_ODD, OFFSET_RECT_ODD, false, 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 1), MAX_NUM_COLS); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 3), MAX_NUM_COLS + 4); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 5), 0); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 7), 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 9), 2); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 11), 3); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 13), 4); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 15), 20); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 17), 21); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 19), 22); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 21), MAX_NUM_COLS - 1); graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, 23), MAX_NUM_COLS + 1); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_odd_offset_odd_rows_no_clip"))); // Test to make sure drawing on all rows creates checkerboard pattern setup_test_aa_sw(&ctx, fb, OFFSET_RECT_ODD, OFFSET_RECT_ODD, false, 1); for (int16_t row = 0; row < MAX_NUM_ROWS; row++) { graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, row), MAX_NUM_COLS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_odd_offset_checkerboard_no_clip"))); // Clipping on even boundaries - no offset setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_EVEN, OFFSET_RECT_ODD, false, 1); for (int16_t row = 0; row < MAX_NUM_ROWS; row++) { graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, row), MAX_NUM_COLS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_odd_offset_even_clip"))); // Clipping on odd boundaries - no offset setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_ODD, OFFSET_RECT_ODD, false, 1); for (int16_t row = 0; row < MAX_NUM_ROWS; row++) { graphics_draw_horizontal_line_dotted(&ctx, GPoint(0, row), MAX_NUM_COLS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_horiz_dotted_line_odd_offset_odd_clip"))); } void test_graphics_draw_line___origin_vertical_dotted(void) { GContext ctx; test_graphics_context_init(&ctx, fb); // Test odd and even cols draw appropriately setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(12, 6), 10); graphics_draw_vertical_line_dotted(&ctx, GPoint(23, 6), 10); graphics_draw_vertical_line_dotted(&ctx, GPoint(13, 7), 10); graphics_draw_vertical_line_dotted(&ctx, GPoint(24, 7), 10); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_origin_no_clip"))); // Even cols of different lengths setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(0, 0), MAX_NUM_ROWS); graphics_draw_vertical_line_dotted(&ctx, GPoint(2, 0), MAX_NUM_ROWS + 4); graphics_draw_vertical_line_dotted(&ctx, GPoint(4, 0), 0); graphics_draw_vertical_line_dotted(&ctx, GPoint(6, 0), 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(8, 0), 2); graphics_draw_vertical_line_dotted(&ctx, GPoint(10, 0), 3); graphics_draw_vertical_line_dotted(&ctx, GPoint(12, 0), 4); graphics_draw_vertical_line_dotted(&ctx, GPoint(14, 0), 20); graphics_draw_vertical_line_dotted(&ctx, GPoint(16, 0), 21); graphics_draw_vertical_line_dotted(&ctx, GPoint(18, 0), 22); graphics_draw_vertical_line_dotted(&ctx, GPoint(20, 0), MAX_NUM_ROWS - 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(22, 0), MAX_NUM_ROWS + 1 ); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_origin_even_cols_no_clip"))); // Odd cols of different lengths setup<|fim_middle|>(&ctx, GPoint(0, 22), MAX_NUM_COLS + 1)<|endoftext|>
prefix_only
argument_list
tests/fw/graphics/test_graphics_draw_line.c
0), 2); graphics_draw_vertical_line_dotted(&ctx, GPoint(10, 0), 3); graphics_draw_vertical_line_dotted(&ctx, GPoint(12, 0), 4); graphics_draw_vertical_line_dotted(&ctx, GPoint(14, 0), 20); graphics_draw_vertical_line_dotted(&ctx, GPoint(16, 0), 21); graphics_draw_vertical_line_dotted(&ctx, GPoint(18, 0), 22); graphics_draw_vertical_line_dotted(&ctx, GPoint(20, 0), MAX_NUM_ROWS - 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(22, 0), MAX_NUM_ROWS + 1 ); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_odd_offset_even_cols_no_clip"))); // Odd cols of different lengths setup_test_aa_sw(&ctx, fb, OFFSET_RECT_ODD, OFFSET_RECT_ODD, false, 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(1, 0), MAX_NUM_ROWS); graphics_draw_vertical_line_dotted(&ctx, GPoint(3, 0), MAX_NUM_ROWS + 4); graphics_draw_vertical_line_dotted(&ctx, GPoint(5, 0), 0); graphics_draw_vertical_line_dotted(&ctx, GPoint(7, 0), 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(9, 0), 2); graphics_draw_vertical_line_dotted(&ctx, GPoint(11, 0), 3); graphics_draw_vertical_line_dotted(&ctx, GPoint(13, 0), 4); graphics_draw_vertical_line_dotted(&ctx, GPoint(15, 0), 20); graphics_draw_vertical_line_dotted(&ctx, GPoint(17, 0), 21); graphics_draw_vertical_line_dotted(&ctx, GPoint(19, 0), 22); graphics_draw_vertical_line_dotted(&ctx, GPoint(21, 0), MAX_NUM_ROWS - 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(23, 0), MAX_NUM_ROWS + 1 ); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_odd_offset_odd_cols_no_clip"))); // Test to make sure drawing on all cols creates checkerboard pattern setup_test_aa_sw(&ctx, fb, OFFSET_RECT_ODD, OFFSET_RECT_ODD, false, 1); for (int16_t col = 0; col < MAX_NUM_COLS; col++) { graphics_draw_vertical_line_dotted(&ctx, GPoint(col, 0), MAX_NUM_ROWS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_odd_offset_checkerboard_no_clip"))); // Clipping on even boundaries - no offset setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_EVEN, OFFSET_RECT_ODD, false, 1); for (int16_t col = 0; col < MAX_NUM_COLS; col++) { graphics_draw_vertical_line_dotted(&ctx, GPoint(col, 0), MAX_NUM_ROWS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_odd_offset_even_clip"))); // Clipping on odd boundaries - no offset setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_ODD, OFFSET_RECT_ODD, false, 1); for (int16_t col = 0; col < MAX_NUM_COLS; col++) { graphics_draw_vertical_line_dotted(&ctx, GPoint(col, 0), MAX_NUM_ROWS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_odd_offset_odd_clip"))); } void test_graphics_draw_line__dotted_cross(void) { GContext ctx; test_graphics_context_init(&ctx, fb); // Test horizontal and vertical lines cross appropriately setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 1); // cross - even vert, odd horiz graphics_draw_vertical_line_dotted(&ctx, GPoint(10, 10), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(5, 15), 10); // cross - odd vert, even horiz graphics_draw_vertical_line_dotted(&ctx, GPoint(41, 11), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(36, 16), 10); // T facing up graphics_draw_vertical_line_dotted(&ctx, GPoint(70, 15), 5); graphics_draw_horizontal_line_dotted(&ctx, GPoint(65, 15), 10); // T facing down graphics_draw_vertical_line_dotted(&ctx, GPoint(101, 11), 5); graphics_draw_horizontal_line_dotted(&ctx, GPoint(96, 16), 10); // cross - even vert, even horiz graphics_draw_vertical_line_dotted(&ctx, GPoint(10, 32), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(4, 36), 10); // cross - odd vert, odd horiz graphics_draw_vertical_line_dotted(&ctx, GPoint(41, 33), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(37, 37), 10); // T facing up - lined up graphics_draw_vertical_line_dotted
(&ctx, GPoint(70, 36), 5)
<|repo_name|>pebble <|file_sep|>tests/fw/graphics/test_graphics_draw_line.c <|fim_prefix|>0), 2); graphics_draw_vertical_line_dotted(&ctx, GPoint(10, 0), 3); graphics_draw_vertical_line_dotted(&ctx, GPoint(12, 0), 4); graphics_draw_vertical_line_dotted(&ctx, GPoint(14, 0), 20); graphics_draw_vertical_line_dotted(&ctx, GPoint(16, 0), 21); graphics_draw_vertical_line_dotted(&ctx, GPoint(18, 0), 22); graphics_draw_vertical_line_dotted(&ctx, GPoint(20, 0), MAX_NUM_ROWS - 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(22, 0), MAX_NUM_ROWS + 1 ); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_odd_offset_even_cols_no_clip"))); // Odd cols of different lengths setup_test_aa_sw(&ctx, fb, OFFSET_RECT_ODD, OFFSET_RECT_ODD, false, 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(1, 0), MAX_NUM_ROWS); graphics_draw_vertical_line_dotted(&ctx, GPoint(3, 0), MAX_NUM_ROWS + 4); graphics_draw_vertical_line_dotted(&ctx, GPoint(5, 0), 0); graphics_draw_vertical_line_dotted(&ctx, GPoint(7, 0), 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(9, 0), 2); graphics_draw_vertical_line_dotted(&ctx, GPoint(11, 0), 3); graphics_draw_vertical_line_dotted(&ctx, GPoint(13, 0), 4); graphics_draw_vertical_line_dotted(&ctx, GPoint(15, 0), 20); graphics_draw_vertical_line_dotted(&ctx, GPoint(17, 0), 21); graphics_draw_vertical_line_dotted(&ctx, GPoint(19, 0), 22); graphics_draw_vertical_line_dotted(&ctx, GPoint(21, 0), MAX_NUM_ROWS - 1); graphics_draw_vertical_line_dotted(&ctx, GPoint(23, 0), MAX_NUM_ROWS + 1 ); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_odd_offset_odd_cols_no_clip"))); // Test to make sure drawing on all cols creates checkerboard pattern setup_test_aa_sw(&ctx, fb, OFFSET_RECT_ODD, OFFSET_RECT_ODD, false, 1); for (int16_t col = 0; col < MAX_NUM_COLS; col++) { graphics_draw_vertical_line_dotted(&ctx, GPoint(col, 0), MAX_NUM_ROWS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_odd_offset_checkerboard_no_clip"))); // Clipping on even boundaries - no offset setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_EVEN, OFFSET_RECT_ODD, false, 1); for (int16_t col = 0; col < MAX_NUM_COLS; col++) { graphics_draw_vertical_line_dotted(&ctx, GPoint(col, 0), MAX_NUM_ROWS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_odd_offset_even_clip"))); // Clipping on odd boundaries - no offset setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_ODD, OFFSET_RECT_ODD, false, 1); for (int16_t col = 0; col < MAX_NUM_COLS; col++) { graphics_draw_vertical_line_dotted(&ctx, GPoint(col, 0), MAX_NUM_ROWS); } cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_vert_dotted_line_odd_offset_odd_clip"))); } void test_graphics_draw_line__dotted_cross(void) { GContext ctx; test_graphics_context_init(&ctx, fb); // Test horizontal and vertical lines cross appropriately setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 1); // cross - even vert, odd horiz graphics_draw_vertical_line_dotted(&ctx, GPoint(10, 10), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(5, 15), 10); // cross - odd vert, even horiz graphics_draw_vertical_line_dotted(&ctx, GPoint(41, 11), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(36, 16), 10); // T facing up graphics_draw_vertical_line_dotted(&ctx, GPoint(70, 15), 5); graphics_draw_horizontal_line_dotted(&ctx, GPoint(65, 15), 10); // T facing down graphics_draw_vertical_line_dotted(&ctx, GPoint(101, 11), 5); graphics_draw_horizontal_line_dotted(&ctx, GPoint(96, 16), 10); // cross - even vert, even horiz graphics_draw_vertical_line_dotted(&ctx, GPoint(10, 32), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(4, 36), 10); // cross - odd vert, odd horiz graphics_draw_vertical_line_dotted(&ctx, GPoint(41, 33), 10); graphics_draw_horizontal_line_dotted(&ctx, GPoint(37, 37), 10); // T facing up - lined up graphics_draw_vertical_line_dotted<|fim_suffix|><|fim_middle|>(&ctx, GPoint(70, 36), 5)<|endoftext|>
prefix_only
argument_list
src/fw/services/normal/weather/weather_service.c
der the License. */ #include "weather_service.h" #include "weather_service_private.h" #include "applib/event_service_client.h" #include "kernel/events.h" #include "kernel/pbl_malloc.h" #include "os/mutex.h" #include "services/common/bluetooth/bluetooth_persistent_storage.h" #include "services/common/comm_session/session_remote_version.h" #include "services/normal/blob_db/watch_app_prefs_db.h" #include "services/normal/blob_db/weather_db.h" #include "services/normal/weather/weather_types.h" #include "system/logging.h" #include "system/passert.h" static int prv_weather_data_list_node_comparator(void *a, void *b) { return ((WeatherDataListNode *)b)->id - ((WeatherDataListNode *)a)->id; } typedef struct WeatherDBIteratorContext { WeatherDataListNode *head; size_t count; SerializedWeatherAppPrefs *serialized_prefs; } WeatherDBIteratorContext; static PebbleMutex *s_mutex; static WeatherLocationForecast *s_default_forecast; static bool prv_entry_update_time_too_old_to_be_valid(const time_t update_time_utc) { const time_t oldest_valid_time_utc = time_start_of_today() - SECONDS_PER_DAY; return (update_time_utc < oldest_valid_time_utc); } static bool prv_fill_forecast_from_entry(WeatherDBEntry *entry, WeatherLocationForecast *forecast_out) { PascalString16List pstring16_list; pstring_project_list_on_serialized_array(&pstring16_list, &entry->pstring16s); PascalString16 *location_pstring = pstring_get_pstring16_from_list(&pstring16_list, WeatherDbStringIndex_LocationName); PascalString16 *phrase_pstring = pstring_get_pstring16_from_list(&pstring16_list, WeatherDbStringIndex_ShortPhrase); const bool is_valid_entry_update_time = (entry->last_update_time_utc != WEATHER_SERVICE_INVALID_DATA_LAST_UPDATE_TIME); const uint16_t location_pstring_length = location_pstring->str_length; if (!is_valid_entry_update_time || (location_pstring_length == 0)) { PBL_LOG(LOG_LEVEL_ERROR, "Invalid entry. Valid UT: %u, location length: %"PRIu16, is_valid_entry_update_time, location_pstring_length); return false; } if (prv_entry_update_time_too_old_to_be_valid(entry->last_update_time_utc)) { PBL_LOG(LOG_LEVEL_WARNING, "Weather entry too old to fill forecast"); return false; } *forecast_out = (WeatherLocationForecast) { .is_current_location = entry->is_current_location, .current_temp = entry->current_temp, .today_high = entry->today_high_temp, .today_low = entry->today_low_temp, .current_weather_type = entry->current_weather_type, .tomorrow_high = entry->tomorrow_high_temp, .tomorrow_low = entry->tomorrow_low_temp, .tomorrow_weather_type = entry->tomorrow_weather_type, .time_updated_utc = entry->last_update_time_utc, }; // add 1 for null terminator forecast_out->location_name = task_zalloc_check(location_pstring->str_length + 1); pstring_pstring16_to_string(location_pstring, forecast_out->location_name); forecast_out->current_weather_phrase = task_zalloc_check(phrase_pstring->str_length + 1); pstring_pstring16_to_string(phrase_pstring, forecast_out->current_weather_phrase); return true; } static bool prv_get_location_index(Uuid *location, SerializedWeatherAppPrefs *prefs, size_t *index_out) { if (!index_out) { return false; } for (size_t idx = 0; idx < prefs->num_locations; idx++) { if (uuid_equal(location, &prefs->locations[idx])) { *index_out = idx; return true; } } return false; } static void prv_add_to_list_if_valid(WeatherDBKey *key, WeatherDBEntry *entry, void *context) { WeatherDBIteratorContext *iterator_context = context; SerializedWeatherAppPrefs *prefs = iterator_context->serialized_prefs; char key_string_buffer[UUID_STRING_BUFFER_LENGTH] = {0}; size_t location_index; if (!prv_get_location_index(key, prefs, &location_index)) { uuid_to_string(key, key_string_buffer); PBL_LOG
(LOG_LEVEL_WARNING, "Weather location %s has no known ordering! Skipping", key_string_buffer)
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/weather/weather_service.c <|fim_prefix|>der the License. */ #include "weather_service.h" #include "weather_service_private.h" #include "applib/event_service_client.h" #include "kernel/events.h" #include "kernel/pbl_malloc.h" #include "os/mutex.h" #include "services/common/bluetooth/bluetooth_persistent_storage.h" #include "services/common/comm_session/session_remote_version.h" #include "services/normal/blob_db/watch_app_prefs_db.h" #include "services/normal/blob_db/weather_db.h" #include "services/normal/weather/weather_types.h" #include "system/logging.h" #include "system/passert.h" static int prv_weather_data_list_node_comparator(void *a, void *b) { return ((WeatherDataListNode *)b)->id - ((WeatherDataListNode *)a)->id; } typedef struct WeatherDBIteratorContext { WeatherDataListNode *head; size_t count; SerializedWeatherAppPrefs *serialized_prefs; } WeatherDBIteratorContext; static PebbleMutex *s_mutex; static WeatherLocationForecast *s_default_forecast; static bool prv_entry_update_time_too_old_to_be_valid(const time_t update_time_utc) { const time_t oldest_valid_time_utc = time_start_of_today() - SECONDS_PER_DAY; return (update_time_utc < oldest_valid_time_utc); } static bool prv_fill_forecast_from_entry(WeatherDBEntry *entry, WeatherLocationForecast *forecast_out) { PascalString16List pstring16_list; pstring_project_list_on_serialized_array(&pstring16_list, &entry->pstring16s); PascalString16 *location_pstring = pstring_get_pstring16_from_list(&pstring16_list, WeatherDbStringIndex_LocationName); PascalString16 *phrase_pstring = pstring_get_pstring16_from_list(&pstring16_list, WeatherDbStringIndex_ShortPhrase); const bool is_valid_entry_update_time = (entry->last_update_time_utc != WEATHER_SERVICE_INVALID_DATA_LAST_UPDATE_TIME); const uint16_t location_pstring_length = location_pstring->str_length; if (!is_valid_entry_update_time || (location_pstring_length == 0)) { PBL_LOG(LOG_LEVEL_ERROR, "Invalid entry. Valid UT: %u, location length: %"PRIu16, is_valid_entry_update_time, location_pstring_length); return false; } if (prv_entry_update_time_too_old_to_be_valid(entry->last_update_time_utc)) { PBL_LOG(LOG_LEVEL_WARNING, "Weather entry too old to fill forecast"); return false; } *forecast_out = (WeatherLocationForecast) { .is_current_location = entry->is_current_location, .current_temp = entry->current_temp, .today_high = entry->today_high_temp, .today_low = entry->today_low_temp, .current_weather_type = entry->current_weather_type, .tomorrow_high = entry->tomorrow_high_temp, .tomorrow_low = entry->tomorrow_low_temp, .tomorrow_weather_type = entry->tomorrow_weather_type, .time_updated_utc = entry->last_update_time_utc, }; // add 1 for null terminator forecast_out->location_name = task_zalloc_check(location_pstring->str_length + 1); pstring_pstring16_to_string(location_pstring, forecast_out->location_name); forecast_out->current_weather_phrase = task_zalloc_check(phrase_pstring->str_length + 1); pstring_pstring16_to_string(phrase_pstring, forecast_out->current_weather_phrase); return true; } static bool prv_get_location_index(Uuid *location, SerializedWeatherAppPrefs *prefs, size_t *index_out) { if (!index_out) { return false; } for (size_t idx = 0; idx < prefs->num_locations; idx++) { if (uuid_equal(location, &prefs->locations[idx])) { *index_out = idx; return true; } } return false; } static void prv_add_to_list_if_valid(WeatherDBKey *key, WeatherDBEntry *entry, void *context) { WeatherDBIteratorContext *iterator_context = context; SerializedWeatherAppPrefs *prefs = iterator_context->serialized_prefs; char key_string_buffer[UUID_STRING_BUFFER_LENGTH] = {0}; size_t location_index; if (!prv_get_location_index(key, prefs, &location_index)) { uuid_to_string(key, key_string_buffer); PBL_LOG<|fim_suffix|><|fim_middle|>(LOG_LEVEL_WARNING, "Weather location %s has no known ordering! Skipping", key_string_buffer)<|endoftext|>
masked_node
argument_list
src/fw/services/common/put_bytes/put_bytes.c
storage_info, s_pb_state.append_offset); kernel_free(storage_info); return success; } static void prv_do_init(void) { bool success = false; InitRequest* request = (InitRequest*) s_pb_state.receiver.buffer; if (prv_is_init_object_type_invalid(request->type)) { goto exit; } uint32_t index; if (!prv_parse_init_index(request, &index)) { goto exit; } uint32_t append_offset = 0; if (s_pb_state.receiver.length > offsetof(InitRequest, extra_info)) { // We compute the offset this way because filename installs can be variable length. In the // future, if we used this feature for files, this would allow for the same struct construction // on the mobile side uint32_t extra_info_offset = s_pb_state.receiver.length - sizeof(InitRequestExtraInfo); InitRequestExtraInfo *info = (InitRequestExtraInfo *)&s_pb_state.receiver.buffer[extra_info_offset]; const uint32_t append_offset_magic = 0xBE4354EF; if (ntohl(info->init_req_magic) == append_offset_magic) { append_offset = ntohl(info->append_offset); PBL_LOG(LOG_LEVEL_INFO, "Restarting FW Update at offset %"PRIu32, append_offset); } } // Setup our state const uint32_t size = ntohl(request->total_size); s_pb_state.total_size = size; s_pb_state.append_offset = append_offset; s_pb_state.remaining_bytes = size; s_pb_state.type = request->type; s_pb_state.has_cookie = request->has_cookie; s_pb_state.index = index; s_pb_state.current_command = PutBytesInit; s_pb_state.is_success = false; // Generate a token const uint32_t r = rand(); s_pb_state.token = MAX(1, r); PBL_LOG(LOG_LEVEL_INFO, "PutBytes Init CB. Type: %d, Idx: %"PRIu32", Size: %"PRIu32" Tok: %"PRIu32, (int) s_pb_state.type, s_pb_state.index, s_pb_state.total_size, s_pb_state.token); success = prv_setup_storage_for_init_request(request, index); s_pb_state.start_ticks = rtc_get_ticks(); bt_driver_analytics_get_conn_event_stats(&s_pb_state.conn_event_stats); if (!success) { PBL_LOG(LOG_LEVEL_WARNING, "Failed to init storage"); goto exit; } PebbleEvent event = { .type = PEBBLE_PUT_BYTES_EVENT, .put_bytes = { .type = PebblePutBytesEventTypeStart, .object_type = s_pb_state.type, .has_cookie = s_pb_state.has_cookie, .progress_percent = 0, .total_size = s_pb_state.total_size, .failed = false }, }; event_put(&event); prv_create_timer_if_needed(); success = new_timer_start(s_pb_state.timer_id, PUT_TIMEOUT_MS, prv_timer_callback, &s_pb_state, 0 /*flags*/); exit: prv_mark_pb_jobs_complete(1); prv_send_response(success ? ResponseAck : ResponseNack, success ? s_pb_state.token : 0); if (!success) { prv_cleanup(); } } static bool prv_check_putrequest_for_errors(const PutRequest *request_hdr, uint32_t tot_request_size); static bool prv_do_put(const PutRequest *request, uint32_t request_size, uint32_t token) { uint32_t data_length = ntohl(request->length); xSemaphoreTake(s_pb_semaphore, portMAX_DELAY); uint32_t remaining_bytes = s_pb_state.remaining_bytes; xSemaphoreGive(s_pb_semaphore); if (prv_check_putrequest_for_errors(request, request_size) || (data_length > remaining_bytes)) { prv_fail(token); return false; } PBL_LOG(LOG_LEVEL_DEBUG, "PutBytes put CB. type: %"PRIu32", length: %"PRIu32, (uint32_t)s_pb_state.type, data_length); pb_storage_append(&s_pb_state.storage, request->data, data_length); xSemaphoreTake(s_pb_semaphore, portMAX_DELAY); s_pb_state.remaining_bytes -= data_length; xSemaphoreGive(s_pb_semaphore); return true; } static void prv_do_commit(void) { uint32_t elapsed_time_ms = ticks_to_milliseconds(rtc_get_ticks() - s_pb_state.start_ticks); const CommitRequest *request = (const CommitRequest *)s_pb_state.receiver.buffer; uint32_t crc = ntohl(request->crc); uint32_t calculated_crc = pb_storage_calculate_crc
; bool commit_succeeded = (calculated_crc == crc); if (elapsed_time_ms > 0) { int bytes_per_sec = (int)((s_pb_state.total_size * 1000) / elapsed_time_ms); PBL_LOG(LOG_LEVEL_DEBUG, "PutBytes pushed %d bytes/sec", bytes_per_sec); } bluetooth_analytics_handle_put_bytes_stats( commit_succeeded, s_pb_state.type, s_pb_state.total_size, elapsed_time_ms, &s_pb_state.conn_event_stats); if (commit_succeeded) { s_pb_state.is_success = true; PBL_LOG(LOG_LEVEL_DEBUG, "PutBytes commit CB. CRC matches! Calculated CRC is 0x%"PRIx32 " expected 0x%"PRIx32, calculated_crc, crc); prv_commit_object(crc); } else { PBL_LOG(LOG_LEVEL_ERROR, "PutBytes commit CB. Calculated CRC is 0x%"PRIx32" expected 0x%"PRIx32, calculated_crc, crc); } s_pb_state.is_success &= commit_succeeded; prv_mark_pb_jobs_complete(1); prv_cleanup_and_send_response((commit_succeeded) ? ResponseAck : ResponseNack); } static bool prv_is_valid_command_for_current_state(PutBytesCommand command) { switch (s_pb_state.current_command) { case PutBytesIdle: return (command == PutBytesInit || command == PutBytesInstall); case PutBytesInit: return (command == PutBytesPut || command == PutBytesAbort); case PutBytesPut: return (command == PutBytesPut || command == PutBytesCommit || command == PutBytesAbort); case PutBytesCommit: case PutBytesAbort: case PutBytesInstall: default: return false; } } static bool prv_is_invalid_command_for_current_state(PutBytesCommand command) { if (!prv_is_valid_command_for_current_state(command)) { PBL_LOG(LOG_LEVEL_ERROR, "PutBytes command 0x%x not permitted in current state 0x%x", command, s_pb_state.current_command); return true; } return false; } static uint32_t prv_parse_token(const PutBytesCommand command, const SharedHeader *header) { if (command == PutBytesInit) { return 0; } return ntohl(header->token); } static bool prv_check_for_state_error(PutBytesCommand cmd, uint32_t token, uint32_t req_length) { const bool has_error = (prv_is_invalid_command_for_current_state(cmd) || prv_has_invalid_request_length(cmd, req_length) || prv_has_invalid_token(cmd, token) || prv_has_invalid_fw_update_state(cmd)); return has_error; } static bool prv_check_putrequest_for_errors(const PutRequest *request_hdr, uint32_t tot_request_size) { uint32_t req_size = tot_request_size - sizeof(PutRequest); uint32_t data_length = ntohl(request_hdr->length); if (data_length > req_size) { PBL_LOG(LOG_LEVEL_ERROR, "Length value longer than buffer"); return true; } uint32_t request_token = prv_parse_token(PutBytesPut, &request_hdr->header); if (prv_check_for_state_error(PutBytesPut, request_token, tot_request_size)) { return true; } return false; } static void prv_process_put_requests_system_task_cb(void *unused) { PutBytesPendingJobs *put_jobs = &s_pb_state.pb_pending_jobs; prv_lock_pb_job_state(); uint8_t num_put_jobs = put_jobs->num_ops_pending; uint8_t read_idx = put_jobs->read_idx; uint32_t initial_remaining_bytes = s_pb_state.remaining_bytes; prv_unlock_pb_job_state(); if (num_put_jobs == 0) { if (s_pb_state.current_command == PutBytesIdle) { // We terminated the PB transfer before we were able to process the PutRequest prv_send_response(ResponseNack, s_pb_state.token); } return; } uint32_t token = 0; for (int job_idx = 0; job_idx < num_put_jobs; job_idx++) { PutBytesJob *job = &put_jobs->job[(read_idx + job_idx) % put_jobs->num_allocated_pb_jobs]; // Process requests until we run into a different command const PutBytesCommand cmd = job->buffer[0]; if (cmd != PutBytesPut) { num_put_jobs = job_idx; break; } token = prv_parse_token(PutBytesPut, (SharedHeader *)job->buffer); if (!prv_do_put((PutRequest *)job->buffer, job->request_length, token)) { //
(&s_pb_state.storage, PutBytesCrcType_Legacy)
<|repo_name|>pebble <|file_sep|>src/fw/services/common/put_bytes/put_bytes.c <|fim_prefix|> storage_info, s_pb_state.append_offset); kernel_free(storage_info); return success; } static void prv_do_init(void) { bool success = false; InitRequest* request = (InitRequest*) s_pb_state.receiver.buffer; if (prv_is_init_object_type_invalid(request->type)) { goto exit; } uint32_t index; if (!prv_parse_init_index(request, &index)) { goto exit; } uint32_t append_offset = 0; if (s_pb_state.receiver.length > offsetof(InitRequest, extra_info)) { // We compute the offset this way because filename installs can be variable length. In the // future, if we used this feature for files, this would allow for the same struct construction // on the mobile side uint32_t extra_info_offset = s_pb_state.receiver.length - sizeof(InitRequestExtraInfo); InitRequestExtraInfo *info = (InitRequestExtraInfo *)&s_pb_state.receiver.buffer[extra_info_offset]; const uint32_t append_offset_magic = 0xBE4354EF; if (ntohl(info->init_req_magic) == append_offset_magic) { append_offset = ntohl(info->append_offset); PBL_LOG(LOG_LEVEL_INFO, "Restarting FW Update at offset %"PRIu32, append_offset); } } // Setup our state const uint32_t size = ntohl(request->total_size); s_pb_state.total_size = size; s_pb_state.append_offset = append_offset; s_pb_state.remaining_bytes = size; s_pb_state.type = request->type; s_pb_state.has_cookie = request->has_cookie; s_pb_state.index = index; s_pb_state.current_command = PutBytesInit; s_pb_state.is_success = false; // Generate a token const uint32_t r = rand(); s_pb_state.token = MAX(1, r); PBL_LOG(LOG_LEVEL_INFO, "PutBytes Init CB. Type: %d, Idx: %"PRIu32", Size: %"PRIu32" Tok: %"PRIu32, (int) s_pb_state.type, s_pb_state.index, s_pb_state.total_size, s_pb_state.token); success = prv_setup_storage_for_init_request(request, index); s_pb_state.start_ticks = rtc_get_ticks(); bt_driver_analytics_get_conn_event_stats(&s_pb_state.conn_event_stats); if (!success) { PBL_LOG(LOG_LEVEL_WARNING, "Failed to init storage"); goto exit; } PebbleEvent event = { .type = PEBBLE_PUT_BYTES_EVENT, .put_bytes = { .type = PebblePutBytesEventTypeStart, .object_type = s_pb_state.type, .has_cookie = s_pb_state.has_cookie, .progress_percent = 0, .total_size = s_pb_state.total_size, .failed = false }, }; event_put(&event); prv_create_timer_if_needed(); success = new_timer_start(s_pb_state.timer_id, PUT_TIMEOUT_MS, prv_timer_callback, &s_pb_state, 0 /*flags*/); exit: prv_mark_pb_jobs_complete(1); prv_send_response(success ? ResponseAck : ResponseNack, success ? s_pb_state.token : 0); if (!success) { prv_cleanup(); } } static bool prv_check_putrequest_for_errors(const PutRequest *request_hdr, uint32_t tot_request_size); static bool prv_do_put(const PutRequest *request, uint32_t request_size, uint32_t token) { uint32_t data_length = ntohl(request->length); xSemaphoreTake(s_pb_semaphore, portMAX_DELAY); uint32_t remaining_bytes = s_pb_state.remaining_bytes; xSemaphoreGive(s_pb_semaphore); if (prv_check_putrequest_for_errors(request, request_size) || (data_length > remaining_bytes)) { prv_fail(token); return false; } PBL_LOG(LOG_LEVEL_DEBUG, "PutBytes put CB. type: %"PRIu32", length: %"PRIu32, (uint32_t)s_pb_state.type, data_length); pb_storage_append(&s_pb_state.storage, request->data, data_length); xSemaphoreTake(s_pb_semaphore, portMAX_DELAY); s_pb_state.remaining_bytes -= data_length; xSemaphoreGive(s_pb_semaphore); return true; } static void prv_do_commit(void) { uint32_t elapsed_time_ms = ticks_to_milliseconds(rtc_get_ticks() - s_pb_state.start_ticks); const CommitRequest *request = (const CommitRequest *)s_pb_state.receiver.buffer; uint32_t crc = ntohl(request->crc); uint32_t calculated_crc = pb_storage_calculate_crc<|fim_suffix|>; bool commit_succeeded = (calculated_crc == crc); if (elapsed_time_ms > 0) { int bytes_per_sec = (int)((s_pb_state.total_size * 1000) / elapsed_time_ms); PBL_LOG(LOG_LEVEL_DEBUG, "PutBytes pushed %d bytes/sec", bytes_per_sec); } bluetooth_analytics_handle_put_bytes_stats( commit_succeeded, s_pb_state.type, s_pb_state.total_size, elapsed_time_ms, &s_pb_state.conn_event_stats); if (commit_succeeded) { s_pb_state.is_success = true; PBL_LOG(LOG_LEVEL_DEBUG, "PutBytes commit CB. CRC matches! Calculated CRC is 0x%"PRIx32 " expected 0x%"PRIx32, calculated_crc, crc); prv_commit_object(crc); } else { PBL_LOG(LOG_LEVEL_ERROR, "PutBytes commit CB. Calculated CRC is 0x%"PRIx32" expected 0x%"PRIx32, calculated_crc, crc); } s_pb_state.is_success &= commit_succeeded; prv_mark_pb_jobs_complete(1); prv_cleanup_and_send_response((commit_succeeded) ? ResponseAck : ResponseNack); } static bool prv_is_valid_command_for_current_state(PutBytesCommand command) { switch (s_pb_state.current_command) { case PutBytesIdle: return (command == PutBytesInit || command == PutBytesInstall); case PutBytesInit: return (command == PutBytesPut || command == PutBytesAbort); case PutBytesPut: return (command == PutBytesPut || command == PutBytesCommit || command == PutBytesAbort); case PutBytesCommit: case PutBytesAbort: case PutBytesInstall: default: return false; } } static bool prv_is_invalid_command_for_current_state(PutBytesCommand command) { if (!prv_is_valid_command_for_current_state(command)) { PBL_LOG(LOG_LEVEL_ERROR, "PutBytes command 0x%x not permitted in current state 0x%x", command, s_pb_state.current_command); return true; } return false; } static uint32_t prv_parse_token(const PutBytesCommand command, const SharedHeader *header) { if (command == PutBytesInit) { return 0; } return ntohl(header->token); } static bool prv_check_for_state_error(PutBytesCommand cmd, uint32_t token, uint32_t req_length) { const bool has_error = (prv_is_invalid_command_for_current_state(cmd) || prv_has_invalid_request_length(cmd, req_length) || prv_has_invalid_token(cmd, token) || prv_has_invalid_fw_update_state(cmd)); return has_error; } static bool prv_check_putrequest_for_errors(const PutRequest *request_hdr, uint32_t tot_request_size) { uint32_t req_size = tot_request_size - sizeof(PutRequest); uint32_t data_length = ntohl(request_hdr->length); if (data_length > req_size) { PBL_LOG(LOG_LEVEL_ERROR, "Length value longer than buffer"); return true; } uint32_t request_token = prv_parse_token(PutBytesPut, &request_hdr->header); if (prv_check_for_state_error(PutBytesPut, request_token, tot_request_size)) { return true; } return false; } static void prv_process_put_requests_system_task_cb(void *unused) { PutBytesPendingJobs *put_jobs = &s_pb_state.pb_pending_jobs; prv_lock_pb_job_state(); uint8_t num_put_jobs = put_jobs->num_ops_pending; uint8_t read_idx = put_jobs->read_idx; uint32_t initial_remaining_bytes = s_pb_state.remaining_bytes; prv_unlock_pb_job_state(); if (num_put_jobs == 0) { if (s_pb_state.current_command == PutBytesIdle) { // We terminated the PB transfer before we were able to process the PutRequest prv_send_response(ResponseNack, s_pb_state.token); } return; } uint32_t token = 0; for (int job_idx = 0; job_idx < num_put_jobs; job_idx++) { PutBytesJob *job = &put_jobs->job[(read_idx + job_idx) % put_jobs->num_allocated_pb_jobs]; // Process requests until we run into a different command const PutBytesCommand cmd = job->buffer[0]; if (cmd != PutBytesPut) { num_put_jobs = job_idx; break; } token = prv_parse_token(PutBytesPut, (SharedHeader *)job->buffer); if (!prv_do_put((PutRequest *)job->buffer, job->request_length, token)) { // <|fim_middle|>(&s_pb_state.storage, PutBytesCrcType_Legacy)<|endoftext|>
masked_node
call_expression
tests/fw/applib/test_text_render.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "applib/graphics/gtypes.h" #include "applib/graphics/text_render.h" #include "clar.h" #include "stubs_applib_resource.h" #include "stubs_app_state.h" #include "stubs_compiled_with_legacy2_sdk.h" #include "stubs_heap.h" #include "stubs_logging.h" #include "stubs_passert.h" #include "stubs_resources.h" #include "stubs_syscalls.h" GBitmap* graphics_context_get_bitmap(GContext* ctx) { return NULL; } void graphics_context_mark_dirty_rect(GContext* ctx, GRect rect) {} const GlyphData* text_resources_get_glyph(FontCache* font_cache, const Codepoint codepoint, FontInfo* fontinfo) { return NULL; } extern int32_t prv_convert_1bit_addr_to_8bit_x(GBitmap *dest_bitmap, uint32_t *block_addr, int32_t y_offset); static int32_t prv_get_8bit_x_from_1bit_x(int32_t dest_1bit_x) { return (((dest_1bit_x / 32) * 4)) * 8; } void test_text_render__convert_1bit_to_8bit_144x168(void) { GSize size = GSize(144, 168); const int row_1bit_size_words = 1 + (size.w - 1) / 32; GBitmap *bitmap = gbitmap_create_blank(size, GBitmapFormat8Bit); uintptr_t base = (uintptr_t)bitmap->addr; int dest_x = 0; int dest_y = 0; uint32_t *block_addr = NULL; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); dest_x = 50; dest_y = 0; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); dest_x = 0; dest_y = 50; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); dest_x = 20; dest_y = 100; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4);
; gbitmap_destroy(bitmap); } void test_text_render__convert_1bit_to_8bit_180x180(void) { GSize size = GSize(180, 180); const int row_1bit_size_words = 1 + (size.w - 1) / 32; GBitmap *bitmap = gbitmap_create_blank(size, GBitmapFormat8Bit); uintptr_t base = (uintptr_t)bitmap->addr; int dest_x = 0; int dest_y = 0; uint32_t *block_addr = NULL; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); dest_x = 50; dest_y = 0; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); dest_x = 0; dest_y = 50; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); dest_x = 20; dest_y = 100; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); gbitmap_destroy(bitmap); }
cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x))
<|repo_name|>pebble <|file_sep|>tests/fw/applib/test_text_render.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "applib/graphics/gtypes.h" #include "applib/graphics/text_render.h" #include "clar.h" #include "stubs_applib_resource.h" #include "stubs_app_state.h" #include "stubs_compiled_with_legacy2_sdk.h" #include "stubs_heap.h" #include "stubs_logging.h" #include "stubs_passert.h" #include "stubs_resources.h" #include "stubs_syscalls.h" GBitmap* graphics_context_get_bitmap(GContext* ctx) { return NULL; } void graphics_context_mark_dirty_rect(GContext* ctx, GRect rect) {} const GlyphData* text_resources_get_glyph(FontCache* font_cache, const Codepoint codepoint, FontInfo* fontinfo) { return NULL; } extern int32_t prv_convert_1bit_addr_to_8bit_x(GBitmap *dest_bitmap, uint32_t *block_addr, int32_t y_offset); static int32_t prv_get_8bit_x_from_1bit_x(int32_t dest_1bit_x) { return (((dest_1bit_x / 32) * 4)) * 8; } void test_text_render__convert_1bit_to_8bit_144x168(void) { GSize size = GSize(144, 168); const int row_1bit_size_words = 1 + (size.w - 1) / 32; GBitmap *bitmap = gbitmap_create_blank(size, GBitmapFormat8Bit); uintptr_t base = (uintptr_t)bitmap->addr; int dest_x = 0; int dest_y = 0; uint32_t *block_addr = NULL; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); dest_x = 50; dest_y = 0; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); dest_x = 0; dest_y = 50; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); dest_x = 20; dest_y = 100; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); <|fim_suffix|>; gbitmap_destroy(bitmap); } void test_text_render__convert_1bit_to_8bit_180x180(void) { GSize size = GSize(180, 180); const int row_1bit_size_words = 1 + (size.w - 1) / 32; GBitmap *bitmap = gbitmap_create_blank(size, GBitmapFormat8Bit); uintptr_t base = (uintptr_t)bitmap->addr; int dest_x = 0; int dest_y = 0; uint32_t *block_addr = NULL; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); dest_x = 50; dest_y = 0; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); dest_x = 0; dest_y = 50; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); dest_x = 20; dest_y = 100; block_addr = (uint32_t *)(uintptr_t)(((dest_y * row_1bit_size_words) + (dest_x / 32)) * 4); cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x)); gbitmap_destroy(bitmap); } <|fim_middle|>cl_assert_equal_i(prv_convert_1bit_addr_to_8bit_x(bitmap, block_addr, dest_y), prv_get_8bit_x_from_1bit_x(dest_x))<|endoftext|>
masked_node
call_expression
src/fw/apps/demo_apps/pebble_shapes.c
_SCALE 10 typedef enum { APP_STATE_FILL_NON_AA, APP_STATE_FILL_AA, APP_STATE_DRAW_NON_AA_NO_SW, APP_STATE_DRAW_AA_NO_SW, APP_STATE_DRAW_NON_AA_SW, APP_STATE_DRAW_AA_SW, // Add more above APP_STATE_NUM_STATES } AppStateIndex; typedef struct AppData { Window window; // Point properties GPoint point_p0; int16_t point_velocity_x; int16_t point_velocity_y; // Line properties GPoint line_p0; GPoint line_p1; int16_t line_velocity_x; int16_t line_velocity_y; // Square properties GRect square; int16_t square_velocity_x; int16_t square_velocity_y; // Rectangle properties GRect rect; int16_t rect_velocity_x; int16_t rect_velocity_y; // Rectangle Round properties GRect rectr; uint16_t rectr_radius; uint16_t rectr_corners_index; int16_t rectr_velocity_x; int16_t rectr_velocity_y; // Circle properties GPoint circle_origin; uint16_t circle_radius; int16_t circle_velocity_x; int16_t circle_velocity_y; GColor circle_color; // Triangle GPath *triangle; GPoint triangle_offset; int16_t triangle_velocity_x; int16_t triangle_velocity_y; // Bucket GPath *bucket; GPoint bucket_offset; int16_t bucket_velocity_x; int16_t bucket_velocity_y; // Generic properties that can be changed as property_index changes bool fill; int16_t color_index; int64_t time_started; uint32_t rendered_frames; bool moving; AppStateIndex state_index; int16_t stroke_width; bool antialiased; } AppData; static void log_state(AppData *data) { switch (data->state_index) { case APP_STATE_FILL_NON_AA: PBL_LOG(LOG_LEVEL_DEBUG, "State: Fill Non-Antialiased; SW: N/A (but currently: %d)", data->stroke_width); break; case APP_STATE_FILL_AA: PBL_LOG(LOG_LEVEL_DEBUG, "State: Fill Antialiased; SW: N/A (but currently: %d)", data->stroke_width); break; case APP_STATE_DRAW_NON_AA_NO_SW: PBL_LOG(LOG_LEVEL_DEBUG, "State: Draw Non-Antialiased; SW: N/A (but currently: %d)", data->stroke_width); break; case APP_STATE_DRAW_AA_NO_SW: PBL_LOG(LOG_LEVEL_DEBUG, "State: Draw Antialiased; SW: N/A (but currently: %d)", data->stroke_width); break; case APP_STATE_DRAW_NON_AA_SW: PBL_LOG(LOG_LEVEL_DEBUG, "State: Draw Non-Antialiased; SW: %d", data->stroke_width); break; case APP_STATE_DRAW_AA_SW: PBL_LOG(LOG_LEVEL_DEBUG, "State: Draw Antialiased; SW: %d", data->stroke_width); break; default: PBL_LOG(LOG_LEVEL_DEBUG, "Unknown State"); break; } } static bool stroke_width_enabled(AppStateIndex state_index) { return ((state_index == APP_STATE_DRAW_AA_SW) || (state_index == APP_STATE_DRAW_NON_AA_SW)); } static void update_state(AppData *data, AppStateIndex state_index) { data->state_index = state_index; data->fill = ((data->state_index == APP_STATE_FILL_NON_AA) || (data->state_index == APP_STATE_FILL_AA)); data->antialiased = ((data->state_index == APP_STATE_DRAW_AA_NO_SW) || (data->state_index == APP_STATE_DRAW_AA_SW) || (data->state_index == APP_STATE_FILL_AA)); } static void back_handler(ClickRecognizerRef recognizer, void *context) { AppData *data = app_state_get_user_data(); update_state(data, ((data->state_index - 1) % APP_STATE_NUM_STATES)); log_state(data); } static void up_handler(ClickRecognizerRef recognizer, void *context) { AppData *data = app_state_get_user_data(); if (stroke_width_enabled(data->state_index)) { data->stroke_width++; if (data->stroke_width >= MAX_STROKE_WIDTH) { data->stroke_width = 1; } } log_state(data); } static void select_handler(ClickRecognizerRef recognizer, void *context) { AppData *data = app_state_get_user_data(); update_state(data, ((data->state_index + 1) % APP_STATE_NUM_STATES)); log_state(data); } static void down_handler(ClickRecognizerRef recognizer, void *context) { AppData *data = app_state_get_user_data(); data->moving = !data->moving;
; } static void click_config_provider(void *context) { window_single_click_subscribe(BUTTON_ID_BACK, back_handler); window_single_click_subscribe(BUTTON_ID_UP, up_handler); window_single_click_subscribe(BUTTON_ID_SELECT, select_handler); window_single_click_subscribe(BUTTON_ID_DOWN, down_handler); } static void prv_move_shape(AppData *data) { for (uint8_t shape = POINT; shape < MAX_SHAPES; shape++) { if (shape == POINT) { // Move the point 4*X per Y data->point_p0.x += (data->point_velocity_x * PIXEL_SPEED_PER_FRAME * 4); if (data->point_p0.x < 0 || data->point_p0.x > data->window.layer.bounds.size.w) { data->point_velocity_x = data->point_velocity_x * -1; } data->point_p0.y += (data->point_velocity_y * PIXEL_SPEED_PER_FRAME); if (data->point_p0.y < 0 || data->point_p0.y > data->window.layer.bounds.size.h) { data->point_velocity_y = data->point_velocity_y * -1; } } else if (shape == LINE) { // Move the line 2*X per Y data->line_p0.x += (data->line_velocity_x * PIXEL_SPEED_PER_FRAME * 2); data->line_p1.x += (data->line_velocity_x * PIXEL_SPEED_PER_FRAME * 2); if (data->line_p0.x < 0 || data->line_p0.x > data->window.layer.bounds.size.w || data->line_p1.x < 0 || data->line_p1.x > data->window.layer.bounds.size.w ) { data->line_velocity_x = data->line_velocity_x * -1; } data->line_p0.y += (data->line_velocity_y * PIXEL_SPEED_PER_FRAME); data->line_p1.y += (data->line_velocity_y * PIXEL_SPEED_PER_FRAME); if (data->line_p0.y < 0 || data->line_p0.y > data->window.layer.bounds.size.h || data->line_p1.y < 0 || data->line_p1.y > data->window.layer.bounds.size.h ) { data->line_velocity_y = data->line_velocity_y * -1; } } else if (shape == SQUARE) { // Move the square X per Y data->square.origin.x += (data->square_velocity_x * PIXEL_SPEED_PER_FRAME); if (data->square.origin.x < 0 || data->square.origin.x + data->square.size.w > data->window.layer.bounds.size.w) { data->square_velocity_x = data->square_velocity_x * -1; } data->square.origin.y += (data->square_velocity_y * PIXEL_SPEED_PER_FRAME); if (data->square.origin.y < 0 || data->square.origin.y + data->square.size.h > data->window.layer.bounds.size.h) { data->square_velocity_y = data->square_velocity_y * -1; } } else if (shape == RECTANGLE) { // Move the rectangle X per 2*Y data->rect.origin.x += (data->rect_velocity_x * PIXEL_SPEED_PER_FRAME); if (data->rect.origin.x < 0 || data->rect.origin.x + data->rect.size.w > data->window.layer.bounds.size.w) { data->rect_velocity_x = data->rect_velocity_x * -1; } data->rect.origin.y += (data->rect_velocity_y * PIXEL_SPEED_PER_FRAME * 2); if (data->rect.origin.y < 0 || data->rect.origin.y + data->rect.size.h > data->window.layer.bounds.size.h) { data->rect_velocity_y = data->rect_velocity_y * -1; } } else if (shape == RECTANGLE_ROUND) { // Move rounded line X per 4*Y data->rectr.origin.x += (data->rectr_velocity_x * PIXEL_SPEED_PER_FRAME); if (data->rectr.origin.x < 0 || data->rectr.origin.x + data->rectr.size.w > data->window.layer.bounds.size.w) { data->rectr_velocity_x = data->rectr_velocity_x * -1; } data->rectr.origin.y += (data->rectr_velocity_y * PIXEL_SPEED_PER_FRAME * 4); if (data->rectr.origin.y < 0 || data->rectr.origin.y + data->rectr.size.h > data->window.layer.bounds.size.h) { data->rectr_velocity_y = data->rectr_velocity_y * -1; } } else if (shape == CIRCLE) { // Move the line X per Y data->circle_origin.x += (data->circle_velocity_x * PIXEL_SPEED_PER_FRAME); if (data->circle_origin.x - data->circle_radius < 0 || data->circle_origin.x + data->circle_radius > data->window.layer.bounds.size.w) { data->circle_velocity_x = data->circle_velocity_x * -1; data->c
log_state(data)
<|repo_name|>pebble <|file_sep|>src/fw/apps/demo_apps/pebble_shapes.c <|fim_prefix|>_SCALE 10 typedef enum { APP_STATE_FILL_NON_AA, APP_STATE_FILL_AA, APP_STATE_DRAW_NON_AA_NO_SW, APP_STATE_DRAW_AA_NO_SW, APP_STATE_DRAW_NON_AA_SW, APP_STATE_DRAW_AA_SW, // Add more above APP_STATE_NUM_STATES } AppStateIndex; typedef struct AppData { Window window; // Point properties GPoint point_p0; int16_t point_velocity_x; int16_t point_velocity_y; // Line properties GPoint line_p0; GPoint line_p1; int16_t line_velocity_x; int16_t line_velocity_y; // Square properties GRect square; int16_t square_velocity_x; int16_t square_velocity_y; // Rectangle properties GRect rect; int16_t rect_velocity_x; int16_t rect_velocity_y; // Rectangle Round properties GRect rectr; uint16_t rectr_radius; uint16_t rectr_corners_index; int16_t rectr_velocity_x; int16_t rectr_velocity_y; // Circle properties GPoint circle_origin; uint16_t circle_radius; int16_t circle_velocity_x; int16_t circle_velocity_y; GColor circle_color; // Triangle GPath *triangle; GPoint triangle_offset; int16_t triangle_velocity_x; int16_t triangle_velocity_y; // Bucket GPath *bucket; GPoint bucket_offset; int16_t bucket_velocity_x; int16_t bucket_velocity_y; // Generic properties that can be changed as property_index changes bool fill; int16_t color_index; int64_t time_started; uint32_t rendered_frames; bool moving; AppStateIndex state_index; int16_t stroke_width; bool antialiased; } AppData; static void log_state(AppData *data) { switch (data->state_index) { case APP_STATE_FILL_NON_AA: PBL_LOG(LOG_LEVEL_DEBUG, "State: Fill Non-Antialiased; SW: N/A (but currently: %d)", data->stroke_width); break; case APP_STATE_FILL_AA: PBL_LOG(LOG_LEVEL_DEBUG, "State: Fill Antialiased; SW: N/A (but currently: %d)", data->stroke_width); break; case APP_STATE_DRAW_NON_AA_NO_SW: PBL_LOG(LOG_LEVEL_DEBUG, "State: Draw Non-Antialiased; SW: N/A (but currently: %d)", data->stroke_width); break; case APP_STATE_DRAW_AA_NO_SW: PBL_LOG(LOG_LEVEL_DEBUG, "State: Draw Antialiased; SW: N/A (but currently: %d)", data->stroke_width); break; case APP_STATE_DRAW_NON_AA_SW: PBL_LOG(LOG_LEVEL_DEBUG, "State: Draw Non-Antialiased; SW: %d", data->stroke_width); break; case APP_STATE_DRAW_AA_SW: PBL_LOG(LOG_LEVEL_DEBUG, "State: Draw Antialiased; SW: %d", data->stroke_width); break; default: PBL_LOG(LOG_LEVEL_DEBUG, "Unknown State"); break; } } static bool stroke_width_enabled(AppStateIndex state_index) { return ((state_index == APP_STATE_DRAW_AA_SW) || (state_index == APP_STATE_DRAW_NON_AA_SW)); } static void update_state(AppData *data, AppStateIndex state_index) { data->state_index = state_index; data->fill = ((data->state_index == APP_STATE_FILL_NON_AA) || (data->state_index == APP_STATE_FILL_AA)); data->antialiased = ((data->state_index == APP_STATE_DRAW_AA_NO_SW) || (data->state_index == APP_STATE_DRAW_AA_SW) || (data->state_index == APP_STATE_FILL_AA)); } static void back_handler(ClickRecognizerRef recognizer, void *context) { AppData *data = app_state_get_user_data(); update_state(data, ((data->state_index - 1) % APP_STATE_NUM_STATES)); log_state(data); } static void up_handler(ClickRecognizerRef recognizer, void *context) { AppData *data = app_state_get_user_data(); if (stroke_width_enabled(data->state_index)) { data->stroke_width++; if (data->stroke_width >= MAX_STROKE_WIDTH) { data->stroke_width = 1; } } log_state(data); } static void select_handler(ClickRecognizerRef recognizer, void *context) { AppData *data = app_state_get_user_data(); update_state(data, ((data->state_index + 1) % APP_STATE_NUM_STATES)); log_state(data); } static void down_handler(ClickRecognizerRef recognizer, void *context) { AppData *data = app_state_get_user_data(); data->moving = !data->moving; <|fim_suffix|>; } static void click_config_provider(void *context) { window_single_click_subscribe(BUTTON_ID_BACK, back_handler); window_single_click_subscribe(BUTTON_ID_UP, up_handler); window_single_click_subscribe(BUTTON_ID_SELECT, select_handler); window_single_click_subscribe(BUTTON_ID_DOWN, down_handler); } static void prv_move_shape(AppData *data) { for (uint8_t shape = POINT; shape < MAX_SHAPES; shape++) { if (shape == POINT) { // Move the point 4*X per Y data->point_p0.x += (data->point_velocity_x * PIXEL_SPEED_PER_FRAME * 4); if (data->point_p0.x < 0 || data->point_p0.x > data->window.layer.bounds.size.w) { data->point_velocity_x = data->point_velocity_x * -1; } data->point_p0.y += (data->point_velocity_y * PIXEL_SPEED_PER_FRAME); if (data->point_p0.y < 0 || data->point_p0.y > data->window.layer.bounds.size.h) { data->point_velocity_y = data->point_velocity_y * -1; } } else if (shape == LINE) { // Move the line 2*X per Y data->line_p0.x += (data->line_velocity_x * PIXEL_SPEED_PER_FRAME * 2); data->line_p1.x += (data->line_velocity_x * PIXEL_SPEED_PER_FRAME * 2); if (data->line_p0.x < 0 || data->line_p0.x > data->window.layer.bounds.size.w || data->line_p1.x < 0 || data->line_p1.x > data->window.layer.bounds.size.w ) { data->line_velocity_x = data->line_velocity_x * -1; } data->line_p0.y += (data->line_velocity_y * PIXEL_SPEED_PER_FRAME); data->line_p1.y += (data->line_velocity_y * PIXEL_SPEED_PER_FRAME); if (data->line_p0.y < 0 || data->line_p0.y > data->window.layer.bounds.size.h || data->line_p1.y < 0 || data->line_p1.y > data->window.layer.bounds.size.h ) { data->line_velocity_y = data->line_velocity_y * -1; } } else if (shape == SQUARE) { // Move the square X per Y data->square.origin.x += (data->square_velocity_x * PIXEL_SPEED_PER_FRAME); if (data->square.origin.x < 0 || data->square.origin.x + data->square.size.w > data->window.layer.bounds.size.w) { data->square_velocity_x = data->square_velocity_x * -1; } data->square.origin.y += (data->square_velocity_y * PIXEL_SPEED_PER_FRAME); if (data->square.origin.y < 0 || data->square.origin.y + data->square.size.h > data->window.layer.bounds.size.h) { data->square_velocity_y = data->square_velocity_y * -1; } } else if (shape == RECTANGLE) { // Move the rectangle X per 2*Y data->rect.origin.x += (data->rect_velocity_x * PIXEL_SPEED_PER_FRAME); if (data->rect.origin.x < 0 || data->rect.origin.x + data->rect.size.w > data->window.layer.bounds.size.w) { data->rect_velocity_x = data->rect_velocity_x * -1; } data->rect.origin.y += (data->rect_velocity_y * PIXEL_SPEED_PER_FRAME * 2); if (data->rect.origin.y < 0 || data->rect.origin.y + data->rect.size.h > data->window.layer.bounds.size.h) { data->rect_velocity_y = data->rect_velocity_y * -1; } } else if (shape == RECTANGLE_ROUND) { // Move rounded line X per 4*Y data->rectr.origin.x += (data->rectr_velocity_x * PIXEL_SPEED_PER_FRAME); if (data->rectr.origin.x < 0 || data->rectr.origin.x + data->rectr.size.w > data->window.layer.bounds.size.w) { data->rectr_velocity_x = data->rectr_velocity_x * -1; } data->rectr.origin.y += (data->rectr_velocity_y * PIXEL_SPEED_PER_FRAME * 4); if (data->rectr.origin.y < 0 || data->rectr.origin.y + data->rectr.size.h > data->window.layer.bounds.size.h) { data->rectr_velocity_y = data->rectr_velocity_y * -1; } } else if (shape == CIRCLE) { // Move the line X per Y data->circle_origin.x += (data->circle_velocity_x * PIXEL_SPEED_PER_FRAME); if (data->circle_origin.x - data->circle_radius < 0 || data->circle_origin.x + data->circle_radius > data->window.layer.bounds.size.w) { data->circle_velocity_x = data->circle_velocity_x * -1; data->c<|fim_middle|>log_state(data)<|endoftext|>
masked_node
call_expression
src/bluetooth-fw/da1468x/controller/main/src/gatt_client_discovery.c
ense is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gatt_client_discovery.h" #include "connection.h" #include "gatt_wrapper.h" #include "hc_protocol/hc_endpoint_discovery.h" #include "kernel/pbl_malloc.h" #include "ppogatt_emulated_server_wa.h" #include "system/logging.h" #include "system/passert.h" #include "util/uuid.h" // Dialog Headers #include "ble_gatt.h" #include "ble_gattc.h" #include "rwble_hl_error.h" #include "ble_uuid.h" #include <bluetooth/bluetooth_types.h> #include <bluetooth/gatt_service_types.h> #include <bluetooth/pebble_bt.h> #include <util/uuid.h> #define GATT_SERVICE_UUID ((uint16_t) 0x1801) #define GATT_SERVICE_CHANGED_CHARACTERISTIC_UUID ((uint16_t) 0x2A05) #define GATT_CCCD_UUID ((uint16_t) 0x2902) // Converts from a Dialog 'att_uuid_t' to firmware 'uuid' representation static void prv_att_uuid_to_uuid(const att_uuid_t *att_uuid, Uuid *uuid) { if (att_uuid->type == ATT_UUID_16) { uint16_t uuid16 = att_uuid->uuid16; *uuid = (Uuid){ BT_UUID_EXPAND(uuid16) }; } else if (att_uuid->type == ATT_UUID_128) { *uuid = UuidMakeFromLEBytes(att_uuid->uuid128); } else { // should never happen PBL_ASSERTN(0); } } T_STATIC HcProtocolDiscoveryServiceFoundPayload *prv_gatt_client_discovery_build_gatt_service( const ble_evt_gattc_browse_svc_t *svc, uint32_t *payload_size) { uint8_t type_counts[GATTC_ITEM_NUM_TYPES] = { }; for (int i = 0; i < svc->num_items; i++) { const gattc_item_t *item = &svc->items[i]; if (item->type >= GATTC_ITEM_NUM_TYPES) { PBL_LOG(LOG_LEVEL_ERROR, "Unexpected gattc type: 0x%x!", (int)item->type); } type_counts[item->type]++; } uint32_t blob_size = COMPUTE_GATTSERVICE_SIZE_BYTES( type_counts[GATTC_ITEM_TYPE_CHARACTERISTIC], type_counts[GATTC_ITEM_TYPE_DESCRIPTOR], type_counts[GATTC_ITEM_TYPE_INCLUDE]); uint32_t payload_extra_size = sizeof(HcProtocolDiscoveryServiceFoundPayload) - sizeof(GATTService); *payload_size = payload_extra_size + blob_size; HcProtocolDiscoveryServiceFoundPayload *payload = kernel_zalloc_check(*payload_size); GATTService *service = &payload->service; uint16_t base_handle = svc->start_h; *service = (GATTService) { .size_bytes = blob_size, .att_handle = base_handle, .num_characteristics = type_counts[GATTC_ITEM_TYPE_CHARACTERISTIC], .num_descriptors = type_counts[GATTC_ITEM_TYPE_DESCRIPTOR], .num_att_handles_included_services = type_counts[GATTC_ITEM_TYPE_INCLUDE], }; prv_att_uuid_to_uuid(&svc->uuid, &service->uuid); char uuid_str[UUID_STRING_BUFFER_LENGTH]; uuid_to_string(&service->uuid, uuid_str); PBL_LOG(LOG_LEVEL_DEBUG, "Found Service %s Handle: 0x%"PRIx16": 0x%"PRIx16" (%"PRIu32" byte blob)", uuid_str, base_handle, svc->end_h, blob_size); uint16_t *att_handles_included_services = (uint16_t *)((uint8_t *)service + blob_size - sizeof(uint16_t) * type_counts[GATTC_ITEM_TYPE_INCLUDE]); uint16_t att_idx = 0; GATTCharacteristic *char_dest = NULL; uint8_t *end_ptr = (uint8_t *)service->characteristics; // A few notes: // + We expect the descriptors to be part of the last discovered characteristic // + We assume Includes can show up anywhere // + If we find descriptors before any characteristic is found, we bail (it shouldn't happen) for (int i = 0; i < svc->num_items; i++) { const gattc_item_t *item = &svc->items[i]; if (item->type == GATTC_ITEM_TYPE_CHARACTERISTIC) { char_dest = (GATTCharacteristic *)end_ptr; *char_dest = (GATTCharacteristic) { .att_handle_offset = (item->c.value_handle - base_handle), .properties = item->c.properties, }; prv_att_uuid_to_uuid(&item->uuid, &char_dest->uuid); end_ptr += sizeof(GATTCharacteristic); uuid_to_string(&char_dest->uuid, uuid_str);
; } else if (item->type == GATTC_ITEM_TYPE_DESCRIPTOR) { if (char_dest == NULL) { PBL_LOG(LOG_LEVEL_ERROR, "No characteristic found for descriptor! handle=0x%x", (int)item->handle); goto failure; } GATTDescriptor *desc_dest = (GATTDescriptor *)end_ptr; *desc_dest = (GATTDescriptor) { .att_handle_offset = item->handle - base_handle, }; prv_att_uuid_to_uuid(&item->uuid, &desc_dest->uuid); char_dest->num_descriptors++; end_ptr += sizeof(GATTDescriptor); uuid_to_string(&desc_dest->uuid, uuid_str); PBL_LOG(LOG_LEVEL_DEBUG, " Found Descriptor %s Handle 0x%x", uuid_str, item->handle); } else if (item->type == GATTC_ITEM_TYPE_INCLUDE) { att_handles_included_services[att_idx] = item->i.start_h; att_idx++; PBL_LOG(LOG_LEVEL_DEBUG, "Found Include, Start Handle 0x%x", item->i.start_h); } } return payload; failure: kernel_free(payload); return NULL; } static void prv_write_cccd_cb(const ble_evt_gattc_write_completed_t *evt) { if (evt->status != ATT_ERROR_OK) { PBL_LOG(LOG_LEVEL_ERROR, "Failed to write CCCD for idx %d Handle 0x%04X", evt->conn_idx, evt->handle); } } //! Inspects the GATT service discovery event in search for the GATT Profile Service and its //! Service Changed characteristic. In case it's found, its ATT handle is recorded in the //! GAPLEConnection structure (by passing it up to the module. The characteristic's indications //! are subscribed to as well. static void prv_search_service_changed_handle(Connection *connection, const ble_evt_gattc_browse_svc_t *evt) { // Check whether the service is the "GATT Profile Service": att_uuid_t gatt_service_uuid; ble_uuid_create16(GATT_SERVICE_UUID, &gatt_service_uuid); att_uuid_t service_changed_characteristic_uuid; ble_uuid_create16(GATT_SERVICE_CHANGED_CHARACTERISTIC_UUID, &service_changed_characteristic_uuid); // Attempt to find the "Service Changed" characteristic: for (uint16_t i = 0; i < evt->num_items; ++i) { const gattc_item_t *characteristic_info = &evt->items[i]; // Sanity: make sure this is a characteristic if (characteristic_info->type != GATTC_ITEM_TYPE_CHARACTERISTIC) { continue; } if (!ble_uuid_equal(&characteristic_info->uuid, &service_changed_characteristic_uuid)) { continue; } // Found the Service Changed characteristic! att_uuid_t cccd_uuid; ble_uuid_create16(GATT_CCCD_UUID, &cccd_uuid); bool cccd_found = false; // Attempt to find the CCCD: for (uint16_t j = 0; j < evt->num_items; ++j) { const gattc_item_t *descriptor_info = &evt->items[j]; // Sanity: make sure this is a descriptor if (descriptor_info->type != GATTC_ITEM_TYPE_DESCRIPTOR) { continue; } if (!ble_uuid_equal(&cccd_uuid, &descriptor_info->uuid)) { continue; } // Found the CCCD! // ... and finally subscribe to indications: const uint16_t cccd_value = GATT_CCC_INDICATIONS; ble_error_t result = gatt_wrapper_write(evt->conn_idx, descriptor_info->handle, sizeof(cccd_value), (const uint8_t *)&cccd_value, (uintptr_t)prv_write_cccd_cb, GattReqSourceController); if (result != BLE_STATUS_OK) { PBL_LOG(LOG_LEVEL_ERROR, "Failed to write CCCD %d", result); } cccd_found = true; break; } if (!cccd_found) { // gah, Android doesn't seem to create the CCCD, but it does seem to auto-subscribe any // bonded device so let's assume this is what happen and notify the main firmware that we are // subscribed. PBL_LOG(LOG_LEVEL_DEBUG, "No cccd found for service changed characteristic, assuming we are " "auto-subscribed"); } // We've got everything we need, record t
PBL_LOG(LOG_LEVEL_DEBUG, " Found Characteristic %s Handle 0x%"PRIx16, uuid_str, item->c.value_handle)
<|repo_name|>pebble <|file_sep|>src/bluetooth-fw/da1468x/controller/main/src/gatt_client_discovery.c <|fim_prefix|>ense is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gatt_client_discovery.h" #include "connection.h" #include "gatt_wrapper.h" #include "hc_protocol/hc_endpoint_discovery.h" #include "kernel/pbl_malloc.h" #include "ppogatt_emulated_server_wa.h" #include "system/logging.h" #include "system/passert.h" #include "util/uuid.h" // Dialog Headers #include "ble_gatt.h" #include "ble_gattc.h" #include "rwble_hl_error.h" #include "ble_uuid.h" #include <bluetooth/bluetooth_types.h> #include <bluetooth/gatt_service_types.h> #include <bluetooth/pebble_bt.h> #include <util/uuid.h> #define GATT_SERVICE_UUID ((uint16_t) 0x1801) #define GATT_SERVICE_CHANGED_CHARACTERISTIC_UUID ((uint16_t) 0x2A05) #define GATT_CCCD_UUID ((uint16_t) 0x2902) // Converts from a Dialog 'att_uuid_t' to firmware 'uuid' representation static void prv_att_uuid_to_uuid(const att_uuid_t *att_uuid, Uuid *uuid) { if (att_uuid->type == ATT_UUID_16) { uint16_t uuid16 = att_uuid->uuid16; *uuid = (Uuid){ BT_UUID_EXPAND(uuid16) }; } else if (att_uuid->type == ATT_UUID_128) { *uuid = UuidMakeFromLEBytes(att_uuid->uuid128); } else { // should never happen PBL_ASSERTN(0); } } T_STATIC HcProtocolDiscoveryServiceFoundPayload *prv_gatt_client_discovery_build_gatt_service( const ble_evt_gattc_browse_svc_t *svc, uint32_t *payload_size) { uint8_t type_counts[GATTC_ITEM_NUM_TYPES] = { }; for (int i = 0; i < svc->num_items; i++) { const gattc_item_t *item = &svc->items[i]; if (item->type >= GATTC_ITEM_NUM_TYPES) { PBL_LOG(LOG_LEVEL_ERROR, "Unexpected gattc type: 0x%x!", (int)item->type); } type_counts[item->type]++; } uint32_t blob_size = COMPUTE_GATTSERVICE_SIZE_BYTES( type_counts[GATTC_ITEM_TYPE_CHARACTERISTIC], type_counts[GATTC_ITEM_TYPE_DESCRIPTOR], type_counts[GATTC_ITEM_TYPE_INCLUDE]); uint32_t payload_extra_size = sizeof(HcProtocolDiscoveryServiceFoundPayload) - sizeof(GATTService); *payload_size = payload_extra_size + blob_size; HcProtocolDiscoveryServiceFoundPayload *payload = kernel_zalloc_check(*payload_size); GATTService *service = &payload->service; uint16_t base_handle = svc->start_h; *service = (GATTService) { .size_bytes = blob_size, .att_handle = base_handle, .num_characteristics = type_counts[GATTC_ITEM_TYPE_CHARACTERISTIC], .num_descriptors = type_counts[GATTC_ITEM_TYPE_DESCRIPTOR], .num_att_handles_included_services = type_counts[GATTC_ITEM_TYPE_INCLUDE], }; prv_att_uuid_to_uuid(&svc->uuid, &service->uuid); char uuid_str[UUID_STRING_BUFFER_LENGTH]; uuid_to_string(&service->uuid, uuid_str); PBL_LOG(LOG_LEVEL_DEBUG, "Found Service %s Handle: 0x%"PRIx16": 0x%"PRIx16" (%"PRIu32" byte blob)", uuid_str, base_handle, svc->end_h, blob_size); uint16_t *att_handles_included_services = (uint16_t *)((uint8_t *)service + blob_size - sizeof(uint16_t) * type_counts[GATTC_ITEM_TYPE_INCLUDE]); uint16_t att_idx = 0; GATTCharacteristic *char_dest = NULL; uint8_t *end_ptr = (uint8_t *)service->characteristics; // A few notes: // + We expect the descriptors to be part of the last discovered characteristic // + We assume Includes can show up anywhere // + If we find descriptors before any characteristic is found, we bail (it shouldn't happen) for (int i = 0; i < svc->num_items; i++) { const gattc_item_t *item = &svc->items[i]; if (item->type == GATTC_ITEM_TYPE_CHARACTERISTIC) { char_dest = (GATTCharacteristic *)end_ptr; *char_dest = (GATTCharacteristic) { .att_handle_offset = (item->c.value_handle - base_handle), .properties = item->c.properties, }; prv_att_uuid_to_uuid(&item->uuid, &char_dest->uuid); end_ptr += sizeof(GATTCharacteristic); uuid_to_string(&char_dest->uuid, uuid_str); <|fim_suffix|>; } else if (item->type == GATTC_ITEM_TYPE_DESCRIPTOR) { if (char_dest == NULL) { PBL_LOG(LOG_LEVEL_ERROR, "No characteristic found for descriptor! handle=0x%x", (int)item->handle); goto failure; } GATTDescriptor *desc_dest = (GATTDescriptor *)end_ptr; *desc_dest = (GATTDescriptor) { .att_handle_offset = item->handle - base_handle, }; prv_att_uuid_to_uuid(&item->uuid, &desc_dest->uuid); char_dest->num_descriptors++; end_ptr += sizeof(GATTDescriptor); uuid_to_string(&desc_dest->uuid, uuid_str); PBL_LOG(LOG_LEVEL_DEBUG, " Found Descriptor %s Handle 0x%x", uuid_str, item->handle); } else if (item->type == GATTC_ITEM_TYPE_INCLUDE) { att_handles_included_services[att_idx] = item->i.start_h; att_idx++; PBL_LOG(LOG_LEVEL_DEBUG, "Found Include, Start Handle 0x%x", item->i.start_h); } } return payload; failure: kernel_free(payload); return NULL; } static void prv_write_cccd_cb(const ble_evt_gattc_write_completed_t *evt) { if (evt->status != ATT_ERROR_OK) { PBL_LOG(LOG_LEVEL_ERROR, "Failed to write CCCD for idx %d Handle 0x%04X", evt->conn_idx, evt->handle); } } //! Inspects the GATT service discovery event in search for the GATT Profile Service and its //! Service Changed characteristic. In case it's found, its ATT handle is recorded in the //! GAPLEConnection structure (by passing it up to the module. The characteristic's indications //! are subscribed to as well. static void prv_search_service_changed_handle(Connection *connection, const ble_evt_gattc_browse_svc_t *evt) { // Check whether the service is the "GATT Profile Service": att_uuid_t gatt_service_uuid; ble_uuid_create16(GATT_SERVICE_UUID, &gatt_service_uuid); att_uuid_t service_changed_characteristic_uuid; ble_uuid_create16(GATT_SERVICE_CHANGED_CHARACTERISTIC_UUID, &service_changed_characteristic_uuid); // Attempt to find the "Service Changed" characteristic: for (uint16_t i = 0; i < evt->num_items; ++i) { const gattc_item_t *characteristic_info = &evt->items[i]; // Sanity: make sure this is a characteristic if (characteristic_info->type != GATTC_ITEM_TYPE_CHARACTERISTIC) { continue; } if (!ble_uuid_equal(&characteristic_info->uuid, &service_changed_characteristic_uuid)) { continue; } // Found the Service Changed characteristic! att_uuid_t cccd_uuid; ble_uuid_create16(GATT_CCCD_UUID, &cccd_uuid); bool cccd_found = false; // Attempt to find the CCCD: for (uint16_t j = 0; j < evt->num_items; ++j) { const gattc_item_t *descriptor_info = &evt->items[j]; // Sanity: make sure this is a descriptor if (descriptor_info->type != GATTC_ITEM_TYPE_DESCRIPTOR) { continue; } if (!ble_uuid_equal(&cccd_uuid, &descriptor_info->uuid)) { continue; } // Found the CCCD! // ... and finally subscribe to indications: const uint16_t cccd_value = GATT_CCC_INDICATIONS; ble_error_t result = gatt_wrapper_write(evt->conn_idx, descriptor_info->handle, sizeof(cccd_value), (const uint8_t *)&cccd_value, (uintptr_t)prv_write_cccd_cb, GattReqSourceController); if (result != BLE_STATUS_OK) { PBL_LOG(LOG_LEVEL_ERROR, "Failed to write CCCD %d", result); } cccd_found = true; break; } if (!cccd_found) { // gah, Android doesn't seem to create the CCCD, but it does seem to auto-subscribe any // bonded device so let's assume this is what happen and notify the main firmware that we are // subscribed. PBL_LOG(LOG_LEVEL_DEBUG, "No cccd found for service changed characteristic, assuming we are " "auto-subscribed"); } // We've got everything we need, record t<|fim_middle|>PBL_LOG(LOG_LEVEL_DEBUG, " Found Characteristic %s Handle 0x%"PRIx16, uuid_str, item->c.value_handle)<|endoftext|>
masked_node
compound_statement
src/fw/services/normal/timeline/attribute_group.c
oad; int num_group_type_elements; if (type == AttributeGroupType_Action) { num_group_type_elements = ((TimelineItemActionGroup *)group_ptr)->num_actions; } else { num_group_type_elements = ((AddressList *)group_ptr)->num_addresses; } for (int i = 0; i < num_group_type_elements; i++) { AttributeList *group_type_element_attribtue_list; if (type == AttributeGroupType_Action) { group_type_element_attribtue_list = prv_deserialize_action( &((TimelineItemActionGroup *)group_ptr)->actions[i], &cursor, payload_end, buffer, buf_end); } else { group_type_element_attribtue_list = prv_deserialize_address( &((AddressList *)group_ptr)->addresses[i], &cursor, payload_end, buffer, buf_end); } if (!attribute_deserialize_list((char**)&buffer, (char *)buf_end, &cursor, payload_end, *group_type_element_attribtue_list)) { return false; } } return true; } bool attribute_group_deserialize(AttributeGroupType type, AttributeList *attr_list, void *group_ptr, uint8_t *buffer, uint8_t *buf_end, const uint8_t *payload, size_t payload_size) { PBL_ASSERTN(payload != NULL); const uint8_t *payload_end = payload + payload_size; const uint8_t *cursor = payload; if (!attribute_deserialize_list((char**)&buffer, (char*)buf_end, &cursor, payload_end, *attr_list)) { return false; } return prv_deserialize_group_element(type, group_ptr, cursor, payload_end, buffer, buf_end); } // ----------------------------------------------------------------------------- static int prv_get_serialized_action_group_size(TimelineItemActionGroup *action_group) { int size = action_group->num_actions * sizeof(SerializedActionHeader); for (int i = 0; i < action_group->num_actions; i++) { size += attribute_list_get_serialized_size(&action_group->actions[i].attr_list); } return size; } static int prv_get_serialized_address_list_size(AddressList *addr_list) { int size = (addr_list->num_addresses * sizeof(SerializedAddressHeader)); for (int i = 0; i < addr_list->num_addresses; i++) { size += attribute_list_get_serialized_size((AttributeList *)&addr_list->addresses[i].attr_list); } return size; } size_t attribute_group_get_serialized_payload_size(AttributeGroupType type, AttributeList *attr_list, void *group_ptr) { size_t size = 0; if (attr_list) { size += attribute_list_get_serialized_size(attr_list); } if (group_ptr) { if (type == AttributeGroupType_Action) { size += prv_get_serialized_action_group_size((TimelineItemActionGroup *)group_ptr); } else { size += prv_get_serialized_address_list_size((AddressList *)group_ptr); } } return size; } // ----------------------------------------------------------------------------- static AttributeList *prv_serialize_action(TimelineItemAction *action, uint8_t **buffer) { SerializedActionHeader *serialized_action = (SerializedActionHeader *)*buffer; *buffer += sizeof(SerializedActionHeader); serialized_action->id = action->id; serialized_action->type = action->type; serialized_action->num_attributes = action->attr_list.num_attributes; return &action->attr_list; } static AttributeList *prv_serialize_address(Address *address, uint8_t **buffer)
static uint8_t* prv_serialize_group_element(AttributeGroupType type, void *group_ptr, uint8_t *buffer, uint8_t *buf_end) { int num_group_type_elements; if (type == AttributeGroupType_Action) { num_group_type_elements = ((TimelineItemActionGroup *)group_ptr)->num_actions; } else { num_group_type_elements = ((AddressList *)group_ptr)->num_addresses; } for (int i = 0; i < num_group_type_elements; i++) { AttributeList *group_type_element_attribtue_list; if (type == AttributeGroupType_Action) { group_type_element_attribtue_list = prv_serialize_action( &((TimelineItemActionGroup *)group_ptr)->actions[i], &buffer); } else { group_type_element_attribtue_list = prv_serialize_address( &((AddressList *)group_ptr)->addresses[i], &buffer); } PBL_ASSERTN(buffer <= buf_end); buffer += attribute_list_serialize(group_type_element_attribtue_list, buffer, buf_end); } return buffer; } size_t attribute_group_serialize_payload(AttributeGroupType type, AttributeList *attr_list, void *group_ptr, uint8_t *buffer, size_t buffer_size) { PBL_ASSERTN(buffer != NULL); uint8_t *buf_start = buffer; uint8_t *buf_end = buffer + buffer_size; if (attr_list) { buffer += attribute_list_serialize(attr_list, buffer, buf_end); } if (group_ptr) { buffer = prv_serialize_group_element(type, group_ptr, buffer, buf_end); } return buffer - buf_start; }
{ SerializedAddressHeader *serialized_address = (SerializedAddressHeader *)*buffer; *buffer += sizeof(SerializedAddressHeader); serialized_address->uuid = address->id; serialized_address->type = address->type; serialized_address->num_attributes = address->attr_list.num_attributes; return &address->attr_list; }
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/timeline/attribute_group.c <|fim_prefix|>oad; int num_group_type_elements; if (type == AttributeGroupType_Action) { num_group_type_elements = ((TimelineItemActionGroup *)group_ptr)->num_actions; } else { num_group_type_elements = ((AddressList *)group_ptr)->num_addresses; } for (int i = 0; i < num_group_type_elements; i++) { AttributeList *group_type_element_attribtue_list; if (type == AttributeGroupType_Action) { group_type_element_attribtue_list = prv_deserialize_action( &((TimelineItemActionGroup *)group_ptr)->actions[i], &cursor, payload_end, buffer, buf_end); } else { group_type_element_attribtue_list = prv_deserialize_address( &((AddressList *)group_ptr)->addresses[i], &cursor, payload_end, buffer, buf_end); } if (!attribute_deserialize_list((char**)&buffer, (char *)buf_end, &cursor, payload_end, *group_type_element_attribtue_list)) { return false; } } return true; } bool attribute_group_deserialize(AttributeGroupType type, AttributeList *attr_list, void *group_ptr, uint8_t *buffer, uint8_t *buf_end, const uint8_t *payload, size_t payload_size) { PBL_ASSERTN(payload != NULL); const uint8_t *payload_end = payload + payload_size; const uint8_t *cursor = payload; if (!attribute_deserialize_list((char**)&buffer, (char*)buf_end, &cursor, payload_end, *attr_list)) { return false; } return prv_deserialize_group_element(type, group_ptr, cursor, payload_end, buffer, buf_end); } // ----------------------------------------------------------------------------- static int prv_get_serialized_action_group_size(TimelineItemActionGroup *action_group) { int size = action_group->num_actions * sizeof(SerializedActionHeader); for (int i = 0; i < action_group->num_actions; i++) { size += attribute_list_get_serialized_size(&action_group->actions[i].attr_list); } return size; } static int prv_get_serialized_address_list_size(AddressList *addr_list) { int size = (addr_list->num_addresses * sizeof(SerializedAddressHeader)); for (int i = 0; i < addr_list->num_addresses; i++) { size += attribute_list_get_serialized_size((AttributeList *)&addr_list->addresses[i].attr_list); } return size; } size_t attribute_group_get_serialized_payload_size(AttributeGroupType type, AttributeList *attr_list, void *group_ptr) { size_t size = 0; if (attr_list) { size += attribute_list_get_serialized_size(attr_list); } if (group_ptr) { if (type == AttributeGroupType_Action) { size += prv_get_serialized_action_group_size((TimelineItemActionGroup *)group_ptr); } else { size += prv_get_serialized_address_list_size((AddressList *)group_ptr); } } return size; } // ----------------------------------------------------------------------------- static AttributeList *prv_serialize_action(TimelineItemAction *action, uint8_t **buffer) { SerializedActionHeader *serialized_action = (SerializedActionHeader *)*buffer; *buffer += sizeof(SerializedActionHeader); serialized_action->id = action->id; serialized_action->type = action->type; serialized_action->num_attributes = action->attr_list.num_attributes; return &action->attr_list; } static AttributeList *prv_serialize_address(Address *address, uint8_t **buffer) <|fim_suffix|> static uint8_t* prv_serialize_group_element(AttributeGroupType type, void *group_ptr, uint8_t *buffer, uint8_t *buf_end) { int num_group_type_elements; if (type == AttributeGroupType_Action) { num_group_type_elements = ((TimelineItemActionGroup *)group_ptr)->num_actions; } else { num_group_type_elements = ((AddressList *)group_ptr)->num_addresses; } for (int i = 0; i < num_group_type_elements; i++) { AttributeList *group_type_element_attribtue_list; if (type == AttributeGroupType_Action) { group_type_element_attribtue_list = prv_serialize_action( &((TimelineItemActionGroup *)group_ptr)->actions[i], &buffer); } else { group_type_element_attribtue_list = prv_serialize_address( &((AddressList *)group_ptr)->addresses[i], &buffer); } PBL_ASSERTN(buffer <= buf_end); buffer += attribute_list_serialize(group_type_element_attribtue_list, buffer, buf_end); } return buffer; } size_t attribute_group_serialize_payload(AttributeGroupType type, AttributeList *attr_list, void *group_ptr, uint8_t *buffer, size_t buffer_size) { PBL_ASSERTN(buffer != NULL); uint8_t *buf_start = buffer; uint8_t *buf_end = buffer + buffer_size; if (attr_list) { buffer += attribute_list_serialize(attr_list, buffer, buf_end); } if (group_ptr) { buffer = prv_serialize_group_element(type, group_ptr, buffer, buf_end); } return buffer - buf_start; } <|fim_middle|>{ SerializedAddressHeader *serialized_address = (SerializedAddressHeader *)*buffer; *buffer += sizeof(SerializedAddressHeader); serialized_address->uuid = address->id; serialized_address->type = address->type; serialized_address->num_attributes = address->attr_list.num_attributes; return &address->attr_list; }<|endoftext|>
prefix_only
call_expression
src/fw/drivers/flash/micron_n25q/flash.c
m to start the transfer SPI_I2S_DMACmd(FLASH_SPI, SPI_I2S_DMAReq_Tx | SPI_I2S_DMAReq_Rx, ENABLE); } static void do_dma_transfer(void) { xSemaphoreTake(s_flash_state.dma_semaphore, portMAX_DELAY); stop_mode_disable(InhibitorFlash); DMA_Cmd(FLASH_DMA_STREAM, ENABLE); DMA_Cmd(FLASH_TX_DMA_STREAM, ENABLE); xSemaphoreTake(s_flash_state.dma_semaphore, portMAX_DELAY); stop_mode_enable(InhibitorFlash); xSemaphoreGive(s_flash_state.dma_semaphore); } void DMA2_Stream0_IRQHandler(void) { if (DMA_GetITStatus(FLASH_DMA_STREAM, DMA_IT_TCIF3)) { DMA_ClearITPendingBit(FLASH_DMA_STREAM, DMA_IT_TCIF3); NVIC_DisableIRQ(FLASH_DMA_IRQn); signed portBASE_TYPE was_higher_priority_task_woken = pdFALSE; xSemaphoreGiveFromISR(s_flash_state.dma_semaphore, &was_higher_priority_task_woken); portEND_SWITCHING_ISR(was_higher_priority_task_woken); return; //notreached } } static void flash_deep_sleep_enter(void) { assert_usable_state(); if (!s_flash_state.deep_sleep) { flash_start_cmd(); flash_send_and_receive_byte(FLASH_CMD_DEEP_SLEEP); flash_end_cmd(); // guarantee we have actually transitioned to deep sleep delay_us(5); s_flash_state.deep_sleep = true; } } static void flash_deep_sleep_exit(void) { assert_usable_state(); if (s_flash_state.deep_sleep) { flash_start_cmd(); flash_send_and_receive_byte(FLASH_CMD_WAKE); flash_end_cmd(); // wait a sufficient amount of time to enter standby mode // It appears violating these timing conditions can lead to // random bit corruptions on flash writes! delay_us(100); s_flash_state.deep_sleep = false; } } void handle_sleep_when_idle_begin(void) { if (s_flash_state.sleep_when_idle) { flash_deep_sleep_exit(); } } void flash_power_down_for_stop_mode(void) { if (s_flash_state.sleep_when_idle) { if (s_flash_state.enabled) { enable_flash_spi_clock(); flash_deep_sleep_enter(); disable_flash_spi_clock(); } } } void flash_power_up_after_stop_mode(void) { // no need here as this platform doesn't support memory-mappable flash } uint32_t flash_get_sector_base_address(uint32_t addr) { return addr & ~(SECTOR_SIZE_BYTES - 1); } // This simply issues a command to read a specific register static uint8_t prv_flash_get_register(uint8_t command) { flash_start_cmd(); flash_send_and_receive_byte(command); uint8_t reg = flash_read_next_byte(); flash_end_cmd(); return reg; } // This will read the flag status register and check it for the SectorLockStatus flag void prv_check_protection_flag() { uint8_t flag_status_register = prv_flash_get_register(FLASH_CMD_READ_FLAG_STATUS_REG); // assert if we found the flag to be enabled PBL_ASSERTN(!(flag_status_register & N25QFlagStatusBit_SectorLockStatus)); } // This will clear the protection flag error from a previous error. // We call this because the error bits persist across reboots static void prv_clear_flag_status_register(void) { flash_start_cmd(); flash_send_and_receive_byte(FLASH_CMD_CLEAR_FLAG_STATUS_REG); flash_end_cmd(); } /** * Write up to 1 page (256B) of data to flash. start_addr DOES NOT * need to be paged aligned. When writing into the middle of a page * (addr & 0xFFF > 0), overrunning the length of the page will cause * the write to "wrap around" and will modify (i.e. corrupt) data * stored before the starting address within the page. * */ static void flash_write_page(const uint8_t* buffer, uint32_t start_addr, uint16_t buffer_size) { // Ensure that we're not trying to write more data than a single page (256 bytes) PBL_ASSERTN(buffer_size <= FLASH_PAGE_SIZE); PBL_ASSERTN(buffer_size); mutex_assert_held_by_curr_task(s_flash_state.mutex, true /* is_held */); // Writing a zero-length buffer is a no-op. if (buffer_size < 1) { return; } flash_write_enable(); flash_start_cmd(); flash_send_and_receive_byte(FLASH_CMD_PAGE_PROGRAM); flash_send_24b_address(start_addr); while (buffer_size--) { flash_send_and_receive_byte(*buffer); buffer++; }
flash_end_cmd()
<|repo_name|>pebble <|file_sep|>src/fw/drivers/flash/micron_n25q/flash.c <|fim_prefix|>m to start the transfer SPI_I2S_DMACmd(FLASH_SPI, SPI_I2S_DMAReq_Tx | SPI_I2S_DMAReq_Rx, ENABLE); } static void do_dma_transfer(void) { xSemaphoreTake(s_flash_state.dma_semaphore, portMAX_DELAY); stop_mode_disable(InhibitorFlash); DMA_Cmd(FLASH_DMA_STREAM, ENABLE); DMA_Cmd(FLASH_TX_DMA_STREAM, ENABLE); xSemaphoreTake(s_flash_state.dma_semaphore, portMAX_DELAY); stop_mode_enable(InhibitorFlash); xSemaphoreGive(s_flash_state.dma_semaphore); } void DMA2_Stream0_IRQHandler(void) { if (DMA_GetITStatus(FLASH_DMA_STREAM, DMA_IT_TCIF3)) { DMA_ClearITPendingBit(FLASH_DMA_STREAM, DMA_IT_TCIF3); NVIC_DisableIRQ(FLASH_DMA_IRQn); signed portBASE_TYPE was_higher_priority_task_woken = pdFALSE; xSemaphoreGiveFromISR(s_flash_state.dma_semaphore, &was_higher_priority_task_woken); portEND_SWITCHING_ISR(was_higher_priority_task_woken); return; //notreached } } static void flash_deep_sleep_enter(void) { assert_usable_state(); if (!s_flash_state.deep_sleep) { flash_start_cmd(); flash_send_and_receive_byte(FLASH_CMD_DEEP_SLEEP); flash_end_cmd(); // guarantee we have actually transitioned to deep sleep delay_us(5); s_flash_state.deep_sleep = true; } } static void flash_deep_sleep_exit(void) { assert_usable_state(); if (s_flash_state.deep_sleep) { flash_start_cmd(); flash_send_and_receive_byte(FLASH_CMD_WAKE); flash_end_cmd(); // wait a sufficient amount of time to enter standby mode // It appears violating these timing conditions can lead to // random bit corruptions on flash writes! delay_us(100); s_flash_state.deep_sleep = false; } } void handle_sleep_when_idle_begin(void) { if (s_flash_state.sleep_when_idle) { flash_deep_sleep_exit(); } } void flash_power_down_for_stop_mode(void) { if (s_flash_state.sleep_when_idle) { if (s_flash_state.enabled) { enable_flash_spi_clock(); flash_deep_sleep_enter(); disable_flash_spi_clock(); } } } void flash_power_up_after_stop_mode(void) { // no need here as this platform doesn't support memory-mappable flash } uint32_t flash_get_sector_base_address(uint32_t addr) { return addr & ~(SECTOR_SIZE_BYTES - 1); } // This simply issues a command to read a specific register static uint8_t prv_flash_get_register(uint8_t command) { flash_start_cmd(); flash_send_and_receive_byte(command); uint8_t reg = flash_read_next_byte(); flash_end_cmd(); return reg; } // This will read the flag status register and check it for the SectorLockStatus flag void prv_check_protection_flag() { uint8_t flag_status_register = prv_flash_get_register(FLASH_CMD_READ_FLAG_STATUS_REG); // assert if we found the flag to be enabled PBL_ASSERTN(!(flag_status_register & N25QFlagStatusBit_SectorLockStatus)); } // This will clear the protection flag error from a previous error. // We call this because the error bits persist across reboots static void prv_clear_flag_status_register(void) { flash_start_cmd(); flash_send_and_receive_byte(FLASH_CMD_CLEAR_FLAG_STATUS_REG); flash_end_cmd(); } /** * Write up to 1 page (256B) of data to flash. start_addr DOES NOT * need to be paged aligned. When writing into the middle of a page * (addr & 0xFFF > 0), overrunning the length of the page will cause * the write to "wrap around" and will modify (i.e. corrupt) data * stored before the starting address within the page. * */ static void flash_write_page(const uint8_t* buffer, uint32_t start_addr, uint16_t buffer_size) { // Ensure that we're not trying to write more data than a single page (256 bytes) PBL_ASSERTN(buffer_size <= FLASH_PAGE_SIZE); PBL_ASSERTN(buffer_size); mutex_assert_held_by_curr_task(s_flash_state.mutex, true /* is_held */); // Writing a zero-length buffer is a no-op. if (buffer_size < 1) { return; } flash_write_enable(); flash_start_cmd(); flash_send_and_receive_byte(FLASH_CMD_PAGE_PROGRAM); flash_send_24b_address(start_addr); while (buffer_size--) { flash_send_and_receive_byte(*buffer); buffer++; } <|fim_suffix|><|fim_middle|>flash_end_cmd()<|endoftext|>
masked_node
compound_statement
tests/fixtures/activity/step_samples/pbl-25656.c
16}, { 856, 112, 0}, { 920, 80, -48}, { 968, 56, -80}, { 1016, 40, -128}, { 1080, 0, -112}, { 1184, 56, -88}, { 1216, 112, -112}, { 1320, 168, -112}, { 1344, 208, -88}, // 5 seconds { 1096, 248, -120}, { 784, 264, -200}, { 536, 248, -192}, { 456, 256, -184}, { 544, 272, -192}, { 696, 288, -288}, { 872, 312, -344}, { 1088, 320, -328}, { 1216, 384, -328}, { 1088, 376, -248}, { 1136, 360, -232}, { 1248, 392, -256}, { 1416, 352, -160}, { 1488, 304, -32}, { 1360, 232, 104}, { 968, 208, 16}, { 792, 104, -48}, { 656, -72, 8}, { 592, -40, 56}, { 712, -40, 8}, { 880, -40, -16}, { 1192, 16, -32}, { 1232, 0, -80}, { 1136, -32, -192}, { 1408, 64, -112}, // 6 seconds { 1280, 16, -32}, { 1368, 104, -144}, { 1456, 208, -208}, { 1184, 224, -216}, { 752, 176, -224}, { 456, 152, -136}, { 360, 168, -216}, { 416, 192, -152}, { 592, 224, -192}, { 848, 280, -200}, { 1200, 336, -288}, { 1184, 416, -312}, { 1136, 352, -232}, { 1144, 360, -224}, { 1128, 392, -208}, { 1424, 360, -104}, { 1512, 304, -8}, { 1256, 256, 8}, { 864, 192, -40}, { 664, 120, -96}, { 632, 40, -32}, { 672, -32, -64}, { 864, -120, -64}, { 1208, -24, -56}, { 1392, -24, -40}, // 7 seconds { 1280, 0, -24}, { 1304, -8, -104}, { 1360, 88, 64}, { 1320, 32, -104}, { 1456, 152, -80}, { 1240, 136, -128}, { 840, 128, -144}, { 472, 112, -216}, { 296, 120, -272}, { 280, 112, -232}, { 456, 112, -232}, { 808, 168, -248}, { 1360, 312, -312}, { 1192, 384, -344}, { 1184, 328, -248}, { 1056, 312, -192}, { 984, 400, -232}, { 928, 312, -208}, { 1232, 320, -88}, { 1392, 312, -24}, { 1240, 256, 64}, { 880, 224, -48}, { 696, 192, -56}, { 640, 152, -56}, { 688, 128, -40}, // 8 seconds { 816, 32, -32}, { 1024, 0, 16}, { 1224, 16, -64}, { 1208, 48, -48}, { 1152, -32, -136}, { 1344, 40, -96}, { 1064, 24, -120}, { 1224, 48, -176}, { 1328, 104, -144}, { 1104, 168, -192}, { 744, 128, -248}, { 488, 32, -232}, { 392, 80, -192}, { 440, 192, -152}, { 640, 248, -192}, { 936, 264, -224}, { 1192, 272, -320}, { 1112, 264, -352}, { 1168, 288, -296}, { 1288, 288, -224}, { 1136, 328, -256}, { 1192, 272, -168}, { 1232, 232, -64}, { 1200, 272, -80}, { 984, 232, -40}, // 9 seconds { 712, 176, -40}, { 632, 152, -80}, { 672, 136, -48}, { 792, 104, 0}, { 912, 96, -48}, { 1064, 72, -32}, { 1192, 88, -72}, { 1224, 64, -128}, { 1360, 72, -32}, { 1184, 152, -64}, { 1064, 72, -168}, { 1336, 136, -80}, { 1176, 104, -80}, { 840, 160, -144}, { 528, 144, -208}, { 416, 112, -264}, { 400, 160, -120}, { 488, 184, -184}, { 776, 168, -256}, { 1120, 216, -272}, { 1240, 264, -376}, { 1176, 288, -312}, { 1392, 320, -240}, { 1224, 376, -240}, { 1136, 304, -192}, // 10 seconds { 1176, 272, -136}, { 1152, 240, -152}, { 984, 232, -112}, { 784, 184, -96}, { 680, 168, -56}, { 704, 176, -48},
{ 1120, 232, -184}, // 13 seconds { 736, 192, -168}, { 504, 200, -184}, { 408, 192, -192}, { 456, 168, -112}, { 600, 248, -160}, { 752, 336, -184}, { 984, 384, -208}, { 1120, 432, -208}, { 1192, 456, -184}, { 1320, 488, -184}, { 1192, 432, -136}, { 1264, 344, -48}, { 1256, 328, -72}, { 1080, 264, -64}, { 808, 216, -32}, { 608, 160, -88}, { 544, 120, -48}, { 608, 96, 0}, { 760, 96, -32}, { 848, 72, -16}, { 1040, 104, -80}, { 1160, 128, -88}, { 1152, 104, -144}, { 1344, 176, -104}, { 1160, 144, -64}, // 14 seconds { 1216, 152, -144}, { 1360, 208, -152}, { 1136, 200, -152}, { 760, 216, -208}, { 440, 200, -248}, { 352, 184, -216}, { 384, 144, -176}, { 576, 184, -128}, { 792, 264, -232}, { 1040, 344, -224}, { 1048, 376, -248}, { 1096, 344, -232}, { 1176, 360, -184}, { 1120, 376, -192}, { 1120, 384, -176}, { 1240, 336, -104}, { 1208, 296, -56}, { 1096, 256, -32}, { 816, 200, -88}, { 648, 184, -88}, { 600, 152, -80}, { 648, 160, -96}, { 736, 144, -72}, { 840, 128, -80}, { 1040, 160, -128}, // 15 seconds { 1144, 144, -152}, { 1104, 88, -208}, { 1216, 128, -184}, { 1160, 136, -160}, { 1072, 136, -144}, { 1296, 224, -160}, { 1200, 184, -184}, { 912, 216, -152}, { 592, 208, -136}, { 440, 184, -160}, { 416, 176, -112}, { 536, 184, -80}, { 736, 232, -144}, { 1000, 280, -200}, { 1136, 304, -208}, { 1064, 296, -248}, { 1160, 288, -208}, { 1288, 336, -208}, { 1064, 376, -208}, { 1056, 352, -192}, { 1144, 368, -184}, { 1128, 288, -160}, { 992, 184, -88}, { 760, 168, -104}, { 672, 184, -96}, // 16 seconds { 680, 160, -104}, { 760, 144, -48}, { 856, 112, -24}, { 976, 112, -64}, { 1056, 136, -112}, { 1072, 152, -120}, { 1072, 88, -128}, { 1120, 104, -96}, { 1112, 128, -48}, { 1216, 168, -40}, { 1280, 208, -80}, { 1112, 240, -128}, { 832, 232, -168}, { 584, 208, -176}, { 512, 176, -136}, { 528, 152, -128}, { 640, 200, -144}, { 736, 232, -224}, { 928, 272, -232}, { 1088, 296, -320}, { 1176, 312, -328}, { 1360, 312, -264}, { 1264, 336, -256}, { 1136, 312, -152}, { 1176, 328, -128}, // 17 seconds { 1160, 304, -120}, { 1032, 256, -64}, { 816, 192, -32}, { 696, 160, -32}, { 680, 144, -64}, { 728, 136, -16}, { 808, 136, 0}, { 840, 88, -24}, { 984, 120, -40}, { 1096, 128, -56}, { 1072, 96, -136}, { 1192, 160, -136}, { 1136, 160, -104}, { 1240, 200, -80}, { 1312, 168, -168}, { 1144, 176, -168}, { 856, 168, -232}, { 624, 160, -192}, { 496, 168, -160}, { 488, 192, -128}, { 560, 216, -144}, { 696, 216, -208}, { 912, 264, -232}, { 1032, 280, -296}, { 1152, 312, -264}, // 18 seconds { 1312, 312, -224}, { 1280, 360, -232}, { 1120, 368, -176}, { 1144, 360, -128}, { 1208, 328, -136}, { 1136, 288, -80}, { 880, 216, -64}, { 712, 192, -72}, { 696, 136, -48}, { 736, 136, -48}, { 832, 112, 16}, { 896, 48, 16}, { 1
{ 768, 128, -32}, { 880, 112, -24}, { 1008, 64, -32}, { 1160, 40, -96}, { 1144, 48, -96}, { 1272, 56, -104}, { 1240, 96, -16}, { 1096, 56, -64}, { 1304, 104, -80}, { 1304, 112, -56}, { 1016, 144, -136}, { 688, 192, -184}, { 472, 200, -200}, { 392, 192, -152}, { 464, 200, -112}, { 664, 208, -152}, { 1032, 248, -160}, { 1328, 304, -256}, { 1112, 328, -256}, // 11 seconds { 1232, 328, -256}, { 1352, 368, -272}, { 1144, 344, -224}, { 1128, 280, -160}, { 1136, 296, -200}, { 1056, 216, -136}, { 872, 168, -128}, { 696, 168, -120}, { 640, 184, -104}, { 704, 168, -40}, { 808, 168, -32}, { 888, 104, 8}, { 1096, 80, -24}, { 1128, 80, -32}, { 1144, 80, -48}, { 1264, 136, -64}, { 1160, 144, -80}, { 1104, 88, -96}, { 1304, 160, -56}, { 1216, 208, -104}, { 928, 216, -160}, { 608, 200, -168}, { 448, 160, -240}, { 416, 128, -144}, { 528, 152, -96}, // 12 seconds { 736, 248, -144}, { 960, 288, -200}, { 1104, 352, -296}, { 1016, 376, -328}, { 1056, 336, -296}, { 1288, 344, -264}, { 1152, 344, -224}, { 1248, 368, -160}, { 1272, 344, -88}, { 1168, 288, -40}, { 960, 256, -40}, { 744, 200, -88}, { 640, 160, -64}, { 616, 136, -48}, { 704, 136, -32}, { 816, 120, -56}, { 808, 80, -8}, { 984, 80, -80}, { 1120, 112, -96}, { 1104, 96, -160}, { 1264, 96, -104}, { 1224, 96, 0}, { 1360, 184, -120}, { 1392, 208, -184},
<|repo_name|>pebble <|file_sep|>tests/fixtures/activity/step_samples/pbl-25656.c <|fim_prefix|>16}, { 856, 112, 0}, { 920, 80, -48}, { 968, 56, -80}, { 1016, 40, -128}, { 1080, 0, -112}, { 1184, 56, -88}, { 1216, 112, -112}, { 1320, 168, -112}, { 1344, 208, -88}, // 5 seconds { 1096, 248, -120}, { 784, 264, -200}, { 536, 248, -192}, { 456, 256, -184}, { 544, 272, -192}, { 696, 288, -288}, { 872, 312, -344}, { 1088, 320, -328}, { 1216, 384, -328}, { 1088, 376, -248}, { 1136, 360, -232}, { 1248, 392, -256}, { 1416, 352, -160}, { 1488, 304, -32}, { 1360, 232, 104}, { 968, 208, 16}, { 792, 104, -48}, { 656, -72, 8}, { 592, -40, 56}, { 712, -40, 8}, { 880, -40, -16}, { 1192, 16, -32}, { 1232, 0, -80}, { 1136, -32, -192}, { 1408, 64, -112}, // 6 seconds { 1280, 16, -32}, { 1368, 104, -144}, { 1456, 208, -208}, { 1184, 224, -216}, { 752, 176, -224}, { 456, 152, -136}, { 360, 168, -216}, { 416, 192, -152}, { 592, 224, -192}, { 848, 280, -200}, { 1200, 336, -288}, { 1184, 416, -312}, { 1136, 352, -232}, { 1144, 360, -224}, { 1128, 392, -208}, { 1424, 360, -104}, { 1512, 304, -8}, { 1256, 256, 8}, { 864, 192, -40}, { 664, 120, -96}, { 632, 40, -32}, { 672, -32, -64}, { 864, -120, -64}, { 1208, -24, -56}, { 1392, -24, -40}, // 7 seconds { 1280, 0, -24}, { 1304, -8, -104}, { 1360, 88, 64}, { 1320, 32, -104}, { 1456, 152, -80}, { 1240, 136, -128}, { 840, 128, -144}, { 472, 112, -216}, { 296, 120, -272}, { 280, 112, -232}, { 456, 112, -232}, { 808, 168, -248}, { 1360, 312, -312}, { 1192, 384, -344}, { 1184, 328, -248}, { 1056, 312, -192}, { 984, 400, -232}, { 928, 312, -208}, { 1232, 320, -88}, { 1392, 312, -24}, { 1240, 256, 64}, { 880, 224, -48}, { 696, 192, -56}, { 640, 152, -56}, { 688, 128, -40}, // 8 seconds { 816, 32, -32}, { 1024, 0, 16}, { 1224, 16, -64}, { 1208, 48, -48}, { 1152, -32, -136}, { 1344, 40, -96}, { 1064, 24, -120}, { 1224, 48, -176}, { 1328, 104, -144}, { 1104, 168, -192}, { 744, 128, -248}, { 488, 32, -232}, { 392, 80, -192}, { 440, 192, -152}, { 640, 248, -192}, { 936, 264, -224}, { 1192, 272, -320}, { 1112, 264, -352}, { 1168, 288, -296}, { 1288, 288, -224}, { 1136, 328, -256}, { 1192, 272, -168}, { 1232, 232, -64}, { 1200, 272, -80}, { 984, 232, -40}, // 9 seconds { 712, 176, -40}, { 632, 152, -80}, { 672, 136, -48}, { 792, 104, 0}, { 912, 96, -48}, { 1064, 72, -32}, { 1192, 88, -72}, { 1224, 64, -128}, { 1360, 72, -32}, { 1184, 152, -64}, { 1064, 72, -168}, { 1336, 136, -80}, { 1176, 104, -80}, { 840, 160, -144}, { 528, 144, -208}, { 416, 112, -264}, { 400, 160, -120}, { 488, 184, -184}, { 776, 168, -256}, { 1120, 216, -272}, { 1240, 264, -376}, { 1176, 288, -312}, { 1392, 320, -240}, { 1224, 376, -240}, { 1136, 304, -192}, // 10 seconds { 1176, 272, -136}, { 1152, 240, -152}, { 984, 232, -112}, { 784, 184, -96}, { 680, 168, -56}, { 704, 176, -48}, <|fim_suffix|> { 1120, 232, -184}, // 13 seconds { 736, 192, -168}, { 504, 200, -184}, { 408, 192, -192}, { 456, 168, -112}, { 600, 248, -160}, { 752, 336, -184}, { 984, 384, -208}, { 1120, 432, -208}, { 1192, 456, -184}, { 1320, 488, -184}, { 1192, 432, -136}, { 1264, 344, -48}, { 1256, 328, -72}, { 1080, 264, -64}, { 808, 216, -32}, { 608, 160, -88}, { 544, 120, -48}, { 608, 96, 0}, { 760, 96, -32}, { 848, 72, -16}, { 1040, 104, -80}, { 1160, 128, -88}, { 1152, 104, -144}, { 1344, 176, -104}, { 1160, 144, -64}, // 14 seconds { 1216, 152, -144}, { 1360, 208, -152}, { 1136, 200, -152}, { 760, 216, -208}, { 440, 200, -248}, { 352, 184, -216}, { 384, 144, -176}, { 576, 184, -128}, { 792, 264, -232}, { 1040, 344, -224}, { 1048, 376, -248}, { 1096, 344, -232}, { 1176, 360, -184}, { 1120, 376, -192}, { 1120, 384, -176}, { 1240, 336, -104}, { 1208, 296, -56}, { 1096, 256, -32}, { 816, 200, -88}, { 648, 184, -88}, { 600, 152, -80}, { 648, 160, -96}, { 736, 144, -72}, { 840, 128, -80}, { 1040, 160, -128}, // 15 seconds { 1144, 144, -152}, { 1104, 88, -208}, { 1216, 128, -184}, { 1160, 136, -160}, { 1072, 136, -144}, { 1296, 224, -160}, { 1200, 184, -184}, { 912, 216, -152}, { 592, 208, -136}, { 440, 184, -160}, { 416, 176, -112}, { 536, 184, -80}, { 736, 232, -144}, { 1000, 280, -200}, { 1136, 304, -208}, { 1064, 296, -248}, { 1160, 288, -208}, { 1288, 336, -208}, { 1064, 376, -208}, { 1056, 352, -192}, { 1144, 368, -184}, { 1128, 288, -160}, { 992, 184, -88}, { 760, 168, -104}, { 672, 184, -96}, // 16 seconds { 680, 160, -104}, { 760, 144, -48}, { 856, 112, -24}, { 976, 112, -64}, { 1056, 136, -112}, { 1072, 152, -120}, { 1072, 88, -128}, { 1120, 104, -96}, { 1112, 128, -48}, { 1216, 168, -40}, { 1280, 208, -80}, { 1112, 240, -128}, { 832, 232, -168}, { 584, 208, -176}, { 512, 176, -136}, { 528, 152, -128}, { 640, 200, -144}, { 736, 232, -224}, { 928, 272, -232}, { 1088, 296, -320}, { 1176, 312, -328}, { 1360, 312, -264}, { 1264, 336, -256}, { 1136, 312, -152}, { 1176, 328, -128}, // 17 seconds { 1160, 304, -120}, { 1032, 256, -64}, { 816, 192, -32}, { 696, 160, -32}, { 680, 144, -64}, { 728, 136, -16}, { 808, 136, 0}, { 840, 88, -24}, { 984, 120, -40}, { 1096, 128, -56}, { 1072, 96, -136}, { 1192, 160, -136}, { 1136, 160, -104}, { 1240, 200, -80}, { 1312, 168, -168}, { 1144, 176, -168}, { 856, 168, -232}, { 624, 160, -192}, { 496, 168, -160}, { 488, 192, -128}, { 560, 216, -144}, { 696, 216, -208}, { 912, 264, -232}, { 1032, 280, -296}, { 1152, 312, -264}, // 18 seconds { 1312, 312, -224}, { 1280, 360, -232}, { 1120, 368, -176}, { 1144, 360, -128}, { 1208, 328, -136}, { 1136, 288, -80}, { 880, 216, -64}, { 712, 192, -72}, { 696, 136, -48}, { 736, 136, -48}, { 832, 112, 16}, { 896, 48, 16}, { 1<|fim_middle|> { 768, 128, -32}, { 880, 112, -24}, { 1008, 64, -32}, { 1160, 40, -96}, { 1144, 48, -96}, { 1272, 56, -104}, { 1240, 96, -16}, { 1096, 56, -64}, { 1304, 104, -80}, { 1304, 112, -56}, { 1016, 144, -136}, { 688, 192, -184}, { 472, 200, -200}, { 392, 192, -152}, { 464, 200, -112}, { 664, 208, -152}, { 1032, 248, -160}, { 1328, 304, -256}, { 1112, 328, -256}, // 11 seconds { 1232, 328, -256}, { 1352, 368, -272}, { 1144, 344, -224}, { 1128, 280, -160}, { 1136, 296, -200}, { 1056, 216, -136}, { 872, 168, -128}, { 696, 168, -120}, { 640, 184, -104}, { 704, 168, -40}, { 808, 168, -32}, { 888, 104, 8}, { 1096, 80, -24}, { 1128, 80, -32}, { 1144, 80, -48}, { 1264, 136, -64}, { 1160, 144, -80}, { 1104, 88, -96}, { 1304, 160, -56}, { 1216, 208, -104}, { 928, 216, -160}, { 608, 200, -168}, { 448, 160, -240}, { 416, 128, -144}, { 528, 152, -96}, // 12 seconds { 736, 248, -144}, { 960, 288, -200}, { 1104, 352, -296}, { 1016, 376, -328}, { 1056, 336, -296}, { 1288, 344, -264}, { 1152, 344, -224}, { 1248, 368, -160}, { 1272, 344, -88}, { 1168, 288, -40}, { 960, 256, -40}, { 744, 200, -88}, { 640, 160, -64}, { 616, 136, -48}, { 704, 136, -32}, { 816, 120, -56}, { 808, 80, -8}, { 984, 80, -80}, { 1120, 112, -96}, { 1104, 96, -160}, { 1264, 96, -104}, { 1224, 96, 0}, { 1360, 184, -120}, { 1392, 208, -184},<|endoftext|>
masked_node
compound_statement
tests/fw/services/blob_db/test_blob_db_sync.c
ssion != NULL); if (s_num_until_timeout != 0 && s_num_writebacks >= s_num_until_timeout) { fake_regular_timer_trigger(&session->timeout_timer); } else { system_task_add_callback(prv_handle_response_from_phone, session); } return 12345; } BlobDBToken blob_db_endpoint_send_write(BlobDBId db_id, time_t last_updated, const void *key, int key_len, const void *val, int val_len) { return 0; } // Tests //////////////////////// void test_blob_db_sync__initialize(void) { fake_blob_db_set_id(BlobDBIdTest); blob_db_init_dbs(); s_num_until_timeout = 0; s_num_writebacks = 0; } void test_blob_db_sync__cleanup(void) { blob_db_flush(BlobDBIdTest); fake_system_task_callbacks_cleanup(); } void test_blob_db_sync__no_dirty(void) { uint8_t ids[NumBlobDBs]; uint8_t num_ids; blob_db_get_dirty_dbs(ids, &num_ids); cl_assert_equal_i(num_ids, 0); cl_assert(blob_db_get_dirty_list(BlobDBIdTest) == NULL); // insert one char *key = "key"; char *value = "value"; cl_assert_equal_i(S_SUCCESS, blob_db_insert(BlobDBIdTest, (uint8_t *)key, strlen(key), (uint8_t *)value, strlen(value))); blob_db_get_dirty_dbs(ids, &num_ids); cl_assert_equal_i(num_ids, 1); cl_assert(blob_db_get_dirty_list(BlobDBIdTest) != NULL); // mark it synced cl_assert_equal_i(S_SUCCESS, blob_db_mark_synced(BlobDBIdTest, (uint8_t *)key, strlen(key))); blob_db_get_dirty_dbs(ids, &num_ids); cl_assert_equal_i(num_ids, 0); cl_assert(blob_db_get_dirty_list(BlobDBIdTest) == NULL); } static bool prv_list_key_comparator(ListNode *cur_node, void *data) { BlobDBDirtyItem *dirty_item = (BlobDBDirtyItem *)cur_node; char *key = data; return (memcmp(dirty_item->key, key, dirty_item->key_len) == 0); } void test_blob_db_sync__dirty_list(void) { uint8_t ids[NumBlobDBs]; uint8_t num_ids; blob_db_get_dirty_dbs(ids, &num_ids); cl_assert_equal_i(num_ids, 0); BlobDBDirtyItem *dirty_list = blob_db_get_dirty_list(BlobDBIdTest); cl_assert(dirty_list == NULL); blob_db_util_free_dirty_list(dirty_list); char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); // insert all keys for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { blob_db_insert(BlobDBIdTest, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); } // check the dirty list blob_db_get_dirty_dbs(ids, &num_ids); cl_assert_equal_i(num_ids, 1); dirty_list = blob_db_get_dirty_list(BlobDBIdTest); cl_assert_equal_i(list_count(&dirty_list->node), ARRAY_LENGTH(keys)); for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { cl_assert(list_find(&dirty_list->node, prv_list_key_comparator, keys[i]) != NULL); } blob_db_util_free_dirty_list(dirty_list); // mark one as synced and re-check for (int synced_idx = 1; synced_idx < ARRAY_LENGTH(keys); ++synced_idx) { blob_db_mark_synced(BlobDBIdTest, (uint8_t *)keys[synced_idx - 1], key_len); dirty_list = blob_db_get_dirty_list(BlobDBIdTest); cl_assert_equal_i(list_count(&dirty_list->node), ARRAY_LENGTH(keys) - synced_idx); for (int i = synced_idx; i < ARRAY_LENGTH(keys); ++i) { cl_assert(list_find(&dirty_list->node, prv_list_key_comparator, keys[i]) != NULL); } blob_db_util_free_dirty_list(dirty_list); } } void test_blob_db_sync__sync_all(void) { char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); // insert all keys for (int i = 0; i < ARRAY_LENGTH(keys); ++i)
cl_assert(blob_db_sync_db(BlobDBIdTest) == S_SUCCESS); prv_generate_responses_from_phone(); cl_assert_equal_i(s_num_writebacks, 5); } void test_blob_db_sync__sync_oom(void) { char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); // insert all keys for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { blob_db_insert(BlobDBIdTest, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); } cl_assert(blob_db_sync_db(BlobDBIdTest) == S_SUCCESS); // We have built the dirty list, add more entries. // This mimics us performing writes while the sync is ongoing or not having enough memory to // build the initial list char *extra_keys[] = { "keyA", "keyB" }; char *extra_values[] = { "valA", "valB" }; for (int i = 0; i < ARRAY_LENGTH(extra_keys); ++i) { blob_db_insert(BlobDBIdTest, (uint8_t *)extra_keys[i], key_len, (uint8_t *)extra_values[i], value_len); } prv_generate_responses_from_phone(); cl_assert_equal_i(s_num_writebacks, 7); } void test_blob_db_sync__sync_some(void) { char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); // insert all keys, mark some as synced for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { blob_db_insert(BlobDBIdTest, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); // choose two that are not consecutive, that leaves 3 still to be synced if (i == 1 || i == 3) { blob_db_mark_synced(BlobDBIdTest, (uint8_t *)keys[i], key_len); } } cl_assert(blob_db_sync_db(BlobDBIdTest) == S_SUCCESS); prv_generate_responses_from_phone(); cl_assert_equal_i(s_num_writebacks, 3); } void test_blob_db_sync__timeout_and_retry(void) { char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); // insert all keys, mark some as synced for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { blob_db_insert(BlobDBIdTest, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); } s_num_until_timeout = 3; s_num_writebacks = 0; cl_assert(blob_db_sync_db(BlobDBIdTest) == S_SUCCESS); prv_generate_responses_from_phone(); cl_assert_equal_i(s_num_writebacks, s_num_until_timeout); s_num_until_timeout = 0; cl_assert(blob_db_sync_db(BlobDBIdTest) == S_SUCCESS); prv_generate_responses_from_phone(); cl_assert_equal_i(s_num_writebacks, 5); } void test_blob_db_sync__sync_while_syncing(void) { char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { blob_db_insert(BlobDBIdTest, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); } cl_assert(blob_db_sync_db(BlobDBIdTest) == S_SUCCESS); // We should throw an error if we get a sync while a db sync in in progress cl_assert(blob_db_sync_db(BlobDBIdTest) == E_BUSY); // Generate some responses so the sync session gets cleaned up prv_generate_responses_from_phone(); } static void prv_fill_stop_return_session(BlobDBId id) { char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); fake_blob_db_set_id(id); blob_db_init_dbs(); for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { blob_db_insert(id, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); } s_num_writebacks = 0; cl_assert(blob_db_sync_db(id) == S_SUCCESS); } void test_blob_db_sync__find_session(void) { // create a few sync sessions prv_fill_stop_return_session(BlobDBIdTest); prv_
{ blob_db_insert(BlobDBIdTest, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); }
<|repo_name|>pebble <|file_sep|>tests/fw/services/blob_db/test_blob_db_sync.c <|fim_prefix|>ssion != NULL); if (s_num_until_timeout != 0 && s_num_writebacks >= s_num_until_timeout) { fake_regular_timer_trigger(&session->timeout_timer); } else { system_task_add_callback(prv_handle_response_from_phone, session); } return 12345; } BlobDBToken blob_db_endpoint_send_write(BlobDBId db_id, time_t last_updated, const void *key, int key_len, const void *val, int val_len) { return 0; } // Tests //////////////////////// void test_blob_db_sync__initialize(void) { fake_blob_db_set_id(BlobDBIdTest); blob_db_init_dbs(); s_num_until_timeout = 0; s_num_writebacks = 0; } void test_blob_db_sync__cleanup(void) { blob_db_flush(BlobDBIdTest); fake_system_task_callbacks_cleanup(); } void test_blob_db_sync__no_dirty(void) { uint8_t ids[NumBlobDBs]; uint8_t num_ids; blob_db_get_dirty_dbs(ids, &num_ids); cl_assert_equal_i(num_ids, 0); cl_assert(blob_db_get_dirty_list(BlobDBIdTest) == NULL); // insert one char *key = "key"; char *value = "value"; cl_assert_equal_i(S_SUCCESS, blob_db_insert(BlobDBIdTest, (uint8_t *)key, strlen(key), (uint8_t *)value, strlen(value))); blob_db_get_dirty_dbs(ids, &num_ids); cl_assert_equal_i(num_ids, 1); cl_assert(blob_db_get_dirty_list(BlobDBIdTest) != NULL); // mark it synced cl_assert_equal_i(S_SUCCESS, blob_db_mark_synced(BlobDBIdTest, (uint8_t *)key, strlen(key))); blob_db_get_dirty_dbs(ids, &num_ids); cl_assert_equal_i(num_ids, 0); cl_assert(blob_db_get_dirty_list(BlobDBIdTest) == NULL); } static bool prv_list_key_comparator(ListNode *cur_node, void *data) { BlobDBDirtyItem *dirty_item = (BlobDBDirtyItem *)cur_node; char *key = data; return (memcmp(dirty_item->key, key, dirty_item->key_len) == 0); } void test_blob_db_sync__dirty_list(void) { uint8_t ids[NumBlobDBs]; uint8_t num_ids; blob_db_get_dirty_dbs(ids, &num_ids); cl_assert_equal_i(num_ids, 0); BlobDBDirtyItem *dirty_list = blob_db_get_dirty_list(BlobDBIdTest); cl_assert(dirty_list == NULL); blob_db_util_free_dirty_list(dirty_list); char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); // insert all keys for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { blob_db_insert(BlobDBIdTest, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); } // check the dirty list blob_db_get_dirty_dbs(ids, &num_ids); cl_assert_equal_i(num_ids, 1); dirty_list = blob_db_get_dirty_list(BlobDBIdTest); cl_assert_equal_i(list_count(&dirty_list->node), ARRAY_LENGTH(keys)); for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { cl_assert(list_find(&dirty_list->node, prv_list_key_comparator, keys[i]) != NULL); } blob_db_util_free_dirty_list(dirty_list); // mark one as synced and re-check for (int synced_idx = 1; synced_idx < ARRAY_LENGTH(keys); ++synced_idx) { blob_db_mark_synced(BlobDBIdTest, (uint8_t *)keys[synced_idx - 1], key_len); dirty_list = blob_db_get_dirty_list(BlobDBIdTest); cl_assert_equal_i(list_count(&dirty_list->node), ARRAY_LENGTH(keys) - synced_idx); for (int i = synced_idx; i < ARRAY_LENGTH(keys); ++i) { cl_assert(list_find(&dirty_list->node, prv_list_key_comparator, keys[i]) != NULL); } blob_db_util_free_dirty_list(dirty_list); } } void test_blob_db_sync__sync_all(void) { char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); // insert all keys for (int i = 0; i < ARRAY_LENGTH(keys); ++i) <|fim_suffix|> cl_assert(blob_db_sync_db(BlobDBIdTest) == S_SUCCESS); prv_generate_responses_from_phone(); cl_assert_equal_i(s_num_writebacks, 5); } void test_blob_db_sync__sync_oom(void) { char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); // insert all keys for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { blob_db_insert(BlobDBIdTest, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); } cl_assert(blob_db_sync_db(BlobDBIdTest) == S_SUCCESS); // We have built the dirty list, add more entries. // This mimics us performing writes while the sync is ongoing or not having enough memory to // build the initial list char *extra_keys[] = { "keyA", "keyB" }; char *extra_values[] = { "valA", "valB" }; for (int i = 0; i < ARRAY_LENGTH(extra_keys); ++i) { blob_db_insert(BlobDBIdTest, (uint8_t *)extra_keys[i], key_len, (uint8_t *)extra_values[i], value_len); } prv_generate_responses_from_phone(); cl_assert_equal_i(s_num_writebacks, 7); } void test_blob_db_sync__sync_some(void) { char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); // insert all keys, mark some as synced for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { blob_db_insert(BlobDBIdTest, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); // choose two that are not consecutive, that leaves 3 still to be synced if (i == 1 || i == 3) { blob_db_mark_synced(BlobDBIdTest, (uint8_t *)keys[i], key_len); } } cl_assert(blob_db_sync_db(BlobDBIdTest) == S_SUCCESS); prv_generate_responses_from_phone(); cl_assert_equal_i(s_num_writebacks, 3); } void test_blob_db_sync__timeout_and_retry(void) { char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); // insert all keys, mark some as synced for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { blob_db_insert(BlobDBIdTest, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); } s_num_until_timeout = 3; s_num_writebacks = 0; cl_assert(blob_db_sync_db(BlobDBIdTest) == S_SUCCESS); prv_generate_responses_from_phone(); cl_assert_equal_i(s_num_writebacks, s_num_until_timeout); s_num_until_timeout = 0; cl_assert(blob_db_sync_db(BlobDBIdTest) == S_SUCCESS); prv_generate_responses_from_phone(); cl_assert_equal_i(s_num_writebacks, 5); } void test_blob_db_sync__sync_while_syncing(void) { char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { blob_db_insert(BlobDBIdTest, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); } cl_assert(blob_db_sync_db(BlobDBIdTest) == S_SUCCESS); // We should throw an error if we get a sync while a db sync in in progress cl_assert(blob_db_sync_db(BlobDBIdTest) == E_BUSY); // Generate some responses so the sync session gets cleaned up prv_generate_responses_from_phone(); } static void prv_fill_stop_return_session(BlobDBId id) { char *keys[] = { "key1", "key2", "key3", "key4", "key5" }; int key_len = strlen(keys[0]); char *values[] = { "val1", "val2", "val3", "val4", "val5" }; int value_len = strlen(values[0]); fake_blob_db_set_id(id); blob_db_init_dbs(); for (int i = 0; i < ARRAY_LENGTH(keys); ++i) { blob_db_insert(id, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); } s_num_writebacks = 0; cl_assert(blob_db_sync_db(id) == S_SUCCESS); } void test_blob_db_sync__find_session(void) { // create a few sync sessions prv_fill_stop_return_session(BlobDBIdTest); prv_<|fim_middle|>{ blob_db_insert(BlobDBIdTest, (uint8_t *)keys[i], key_len, (uint8_t *)values[i], value_len); }<|endoftext|>
suffix_only
call_expression
src/fw/apps/demo_apps/activity_test.c
; activity_prefs_sleep_insights_set_enabled(true); // History with low median but good sleep over the past few days ActivitySettingsValueHistory sleep_history = { .utc_sec = rtc_get_time(), .values = { 0, // This ends up overwritten anyway by the current sleep value GOOD_SLEEP, GOOD_SLEEP, GOOD_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP } }; // Reset all stored data activity_test_reset(true /*reset_settings*/, true /*tracking_on*/, &sleep_history, NULL); for (int i = 0; i < 3; ++i) { // Change into awake state and capture the sleep before // Walk long enough to overlap with a periodic sleep recomputation prv_feed_steps_min(ACTIVITY_SESSION_UPDATE_MIN + 1); // Do some deep sleep prv_feed_deep_sleep_min(GOOD_SLEEP); // Walk long enough to be registered as "awake" for over 2 hours prv_feed_steps_min((2.5 * MINUTES_PER_HOUR) + ACTIVITY_SESSION_UPDATE_MIN); // Fast forward time rtc_set_time(time_util_get_midnight_of(rtc_get_time()) + 4 * SECONDS_PER_DAY); } activity_prefs_sleep_insights_set_enabled(prev_insights_enabled); prv_test_end(context, passed); } // ------------------------------------------------------------------------------- static void prv_test_activity_reward(void *context) { bool passed = true; // TODO: is this needed here? // Hack to get around midnight rollover bug (only affects tests) rtc_set_time(time_util_get_midnight_of(rtc_get_time())); bool prev_insights_enabled = activity_prefs_activity_insights_are_enabled(); activity_prefs_activity_insights_set_enabled(true); const ActivityScalarStore AVERAGE_STEPS = 1000; // History with low median ActivitySettingsValueHistory step_history = { .utc_sec = rtc_get_time(), .values = { 0, // This ends up overwritten anyway by the current sleep value AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS } }; // Reset all stored data activity_test_reset(true /*reset_settings*/, true /*tracking_on*/, NULL, &step_history); // Walk for about 30 minutes (this should give us over 2500 steps) const int k_num_minutes = 30; // Feed in the data (should see an insight) prv_feed_steps_min(k_num_minutes); // Fast forward a day and check that we update the settings cache when the file changes rtc_set_time(time_util_get_midnight_of(rtc_get_time()) + 1 * SECONDS_PER_DAY); ActivityInsightSettings original_settings; activity_insights_settings_read(ACTIVITY_INSIGHTS_SETTINGS_ACTIVITY_REWARD, &original_settings); ActivityInsightSettings disabled_settings = original_settings; disabled_settings.enabled = false; activity_insights_settings_write(ACTIVITY_INSIGHTS_SETTINGS_ACTIVITY_REWARD, &disabled_settings); prv_feed_steps_min(k_num_minutes); activity_insights_settings_write(ACTIVITY_INSIGHTS_SETTINGS_ACTIVITY_REWARD, &original_settings); activity_prefs_activity_insights_set_enabled(prev_insights_enabled); prv_test_end(context, passed); } // ------------------------------------------------------------------------------- static void prv_test_sleep_summary(void *context) { bool passed = true; // Start at 1am to make sure it doesn't get registered as a nap rtc_set_time(time_util_get_midnight_of(rtc_get_time()) + 1 * SECONDS_PER_HOUR); activity_prefs_sleep_insights_set_enabled(true); const ActivityScalarStore AVERAGE_SLEEP = 2 * MINUTES_PER_HOUR; // History with low median but good sleep over the past few days ActivitySettingsValueHistory sleep_history = { .utc_sec = rtc_get_time(), .values = { 0, // This ends up overwritten anyway by the current sleep value AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP
activity_prefs_sleep_insights_are_enabled()
<|repo_name|>pebble <|file_sep|>src/fw/apps/demo_apps/activity_test.c <|fim_prefix|><|fim_suffix|>; activity_prefs_sleep_insights_set_enabled(true); // History with low median but good sleep over the past few days ActivitySettingsValueHistory sleep_history = { .utc_sec = rtc_get_time(), .values = { 0, // This ends up overwritten anyway by the current sleep value GOOD_SLEEP, GOOD_SLEEP, GOOD_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP } }; // Reset all stored data activity_test_reset(true /*reset_settings*/, true /*tracking_on*/, &sleep_history, NULL); for (int i = 0; i < 3; ++i) { // Change into awake state and capture the sleep before // Walk long enough to overlap with a periodic sleep recomputation prv_feed_steps_min(ACTIVITY_SESSION_UPDATE_MIN + 1); // Do some deep sleep prv_feed_deep_sleep_min(GOOD_SLEEP); // Walk long enough to be registered as "awake" for over 2 hours prv_feed_steps_min((2.5 * MINUTES_PER_HOUR) + ACTIVITY_SESSION_UPDATE_MIN); // Fast forward time rtc_set_time(time_util_get_midnight_of(rtc_get_time()) + 4 * SECONDS_PER_DAY); } activity_prefs_sleep_insights_set_enabled(prev_insights_enabled); prv_test_end(context, passed); } // ------------------------------------------------------------------------------- static void prv_test_activity_reward(void *context) { bool passed = true; // TODO: is this needed here? // Hack to get around midnight rollover bug (only affects tests) rtc_set_time(time_util_get_midnight_of(rtc_get_time())); bool prev_insights_enabled = activity_prefs_activity_insights_are_enabled(); activity_prefs_activity_insights_set_enabled(true); const ActivityScalarStore AVERAGE_STEPS = 1000; // History with low median ActivitySettingsValueHistory step_history = { .utc_sec = rtc_get_time(), .values = { 0, // This ends up overwritten anyway by the current sleep value AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS, AVERAGE_STEPS } }; // Reset all stored data activity_test_reset(true /*reset_settings*/, true /*tracking_on*/, NULL, &step_history); // Walk for about 30 minutes (this should give us over 2500 steps) const int k_num_minutes = 30; // Feed in the data (should see an insight) prv_feed_steps_min(k_num_minutes); // Fast forward a day and check that we update the settings cache when the file changes rtc_set_time(time_util_get_midnight_of(rtc_get_time()) + 1 * SECONDS_PER_DAY); ActivityInsightSettings original_settings; activity_insights_settings_read(ACTIVITY_INSIGHTS_SETTINGS_ACTIVITY_REWARD, &original_settings); ActivityInsightSettings disabled_settings = original_settings; disabled_settings.enabled = false; activity_insights_settings_write(ACTIVITY_INSIGHTS_SETTINGS_ACTIVITY_REWARD, &disabled_settings); prv_feed_steps_min(k_num_minutes); activity_insights_settings_write(ACTIVITY_INSIGHTS_SETTINGS_ACTIVITY_REWARD, &original_settings); activity_prefs_activity_insights_set_enabled(prev_insights_enabled); prv_test_end(context, passed); } // ------------------------------------------------------------------------------- static void prv_test_sleep_summary(void *context) { bool passed = true; // Start at 1am to make sure it doesn't get registered as a nap rtc_set_time(time_util_get_midnight_of(rtc_get_time()) + 1 * SECONDS_PER_HOUR); activity_prefs_sleep_insights_set_enabled(true); const ActivityScalarStore AVERAGE_SLEEP = 2 * MINUTES_PER_HOUR; // History with low median but good sleep over the past few days ActivitySettingsValueHistory sleep_history = { .utc_sec = rtc_get_time(), .values = { 0, // This ends up overwritten anyway by the current sleep value AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP, AVERAGE_SLEEP <|fim_middle|>activity_prefs_sleep_insights_are_enabled()<|endoftext|>
masked_node
argument_list
src/fw/console/prompt_commands.c
than 5% bool passed = ((duration_us >= i) && (duration_us <= ((i * 105) / 100))); if (!passed) { prompt_send_response_fmt(buf, sizeof(buf), "Audit Failed: Expected %"PRIu32", Got %"PRIu32, i, duration_us); } } prompt_send_response("delay_us audit complete"); __enable_irq(); } // Simply parks the chip permanently in stop mode in whatever state it's currently in. This can be // pretty handy when trying to profile power of the chip under certains states // NOTE: If you did not configure with `--nowatchdog`, the HW watchdog will reboot you in ~8s void command_enter_stop(void) { dbgserial_putstr("Entering stop mode indefinitely ... reboot your board to get out!!"); __disable_irq(); RTC_ITConfig(RTC_IT_WUT, DISABLE); RTC_WakeUpCmd(DISABLE); // disable all IRQn_Type >= 0 interrupts for (size_t i = 0; i < ARRAY_LENGTH(NVIC->ISER); i++) { NVIC->ICER[i] = NVIC->ISER[i]; } // disable SysTick SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; enter_stop_mode(); dbgserial_putstr("woah, failed to enter stop mode"); while (1) { } } #ifndef RECOVERY_FW // Create a bunch of fragmentation in the filesystem by creating a large number // of small files and only deleting a small number of them void command_litter_filesystem(void) { char name[10]; for (int i = 0; i < 100; i++) { snprintf(name, sizeof(name), "litter%d", i); int fd = pfs_open(name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 300); if (i % 5 == 0) { pfs_close_and_remove(fd); } else { pfs_close(fd); } } } #endif #endif static GAPLEConnection *prv_get_le_connection_and_print_info(void) { GAPLEConnection *conn = gap_le_connection_any(); if (!conn) { prompt_send_response("No device connected"); } else { char buf[80]; prompt_send_response_fmt(buf, sizeof(buf), "Connected to " BT_DEVICE_ADDRESS_FMT, BT_DEVICE_ADDRESS_XPLODE(conn->device.address)); } return conn; } void command_bt_conn_param_set( char *interval_min_1_25ms, char *interval_max_1_25ms, char *slave_latency_events, char *timeout_10ms) { BleConnectionParamsUpdateReq req = { .interval_min_1_25ms = atoi(interval_min_1_25ms), .interval_max_1_25ms = atoi(interval_max_1_25ms), .slave_latency_events = atoi(slave_latency_events), .supervision_timeout_10ms = atoi(timeout_10ms), }; GAPLEConnection *conn = prv_get_le_connection_and_print_info(); BTDeviceInternal addr = {}; if (conn) { addr.address = conn->device.address; } bt_driver_le_connection_parameter_update(&addr, &req); } // Not in a header because it's really only used from within the gatt_service_changed module extern void gatt_client_discovery_discover_range( GAPLEConnection *connection, ATTHandleRange *hdl_range); void command_bt_disc_start(char *start_handle, char *end_handle) { bt_lock(); { ATTHandleRange range = { .start = atoi(start_handle), .end = atoi(end_handle) }; GAPLEConnection *conn = prv_get_le_connection_and_print_info(); if (conn) { gatt_client_discovery_discover_range(conn, &range); } } bt_unlock(); } void command_bt_disc_stop(void) { bt_lock(); { GAPLEConnection *conn = prv_get_le_connection_and_print_info(); if (conn) { bt_driver_gatt_stop_discovery(conn); } } bt_unlock(); } #if BT_CONTROLLER_DA14681 static TimerID s_sleep_test_timer = TIMER_INVALID_ID; static uint32_t s_num_sleep_iters = 0; static void prv_sleep_timer_test_cb(void *data) { uint32_t count = (uint32_t)data; for (int j = 0; j < 10; j++) { bt_driver_send_sleep_test_cmd(true); psleep(9); } if (count >= s_num_sleep_iters) { bt_driver_send_sleep_test_cmd(false); prompt_send_response("100 % - PASS"); new_timer_delete(s_sleep_test_timer); prompt_command_finish(); } else { char buf[80]; prompt_send_response_fmt(buf, sizeof(buf), "%d %%", (int)((count * 100) / s_num_sleep_iters)); count++; new_timer_start
; } } // Attempts to check that the Dialog chip sleep mode is working correctly by forcing wakeups at // different times. (See PBL-39777). The timeouts delays may seem a little random but I found with // this combo of values I was able to hit the issue on both failing units I have pretty quickly. extern bool bt_test_chip_in_test_mode(void); void command_bt_sleep_check(const char *iters) { s_num_sleep_iters = atoi(iters); // It seems like advertising while doing this makes the issue more likely to happen // (I suspect because there are even more enters/exits from sleep happening) if (bt_test_chip_in_test_mode()) { prompt_send_response("You must run \"bt test stop\" to conduct sleep test!"); return; } prompt_send_response("Starting BT sleep check test"); s_sleep_test_timer = new_timer_create(); new_timer_start(s_sleep_test_timer , 10, prv_sleep_timer_test_cb, (void *)(uintptr_t)0, 0); prompt_command_continues_after_returning(); } void command_btle_unmod_tx_start(char *tx_channel) { bt_driver_start_unmodulated_tx(atoi(tx_channel)); } void command_btle_unmod_tx_stop(void) { bt_driver_stop_unmodulated_tx(); } void command_btle_test_le_tx_start( char *tx_channel, char *tx_packet_length, char *packet_payload_type) { bt_driver_le_transmitter_test( atoi(tx_channel), atoi(tx_packet_length), atoi(packet_payload_type)); } void command_btle_test_rx_start(char *rx_channel) { bt_driver_le_receiver_test(atoi(rx_channel)); } void command_btle_test_end(void) { bt_driver_le_test_end(); } //# if PLATFORM_ROBERT static const char *s_btle_pa_config_strings[3] = { "disable", "enable", "bypass" }; void command_btle_pa_set(char *command) { char buffer[64]; int index; for (index = 0; index < BtlePaConfigCount; ++index) { if (strcmp(command, s_btle_pa_config_strings[index]) == 0) { break; } } if (index >= BtlePaConfigCount) { prompt_send_response_fmt(buffer, sizeof(buffer), "BTLE PA options are: %s, %s, %s", s_btle_pa_config_strings[BtlePaConfig_Disable], s_btle_pa_config_strings[BtlePaConfig_Enable], s_btle_pa_config_strings[BtlePaConfig_Bypass]); } else { bt_driver_le_test_pa(index); prompt_send_response_fmt(buffer, sizeof(buffer), "BTLE PA set to: %s", s_btle_pa_config_strings[index]); } } //# endif #endif extern void hc_endpoint_logging_set_level(uint8_t level); void command_ble_logging_set_level(const char *level) { char buffer[32]; int log_level = atoi(level); if (log_level < 0) { log_level = 0; } else if (log_level > 255) { log_level = 255; } hc_endpoint_logging_set_level(log_level); prompt_send_response_fmt(buffer, 32, "Ble Log level set to: %i", log_level); } extern bool hc_endpoint_logging_get_level(uint8_t *level); void command_ble_logging_get_level(void) { uint8_t log_level; char buffer[32]; if (!hc_endpoint_logging_get_level(&log_level)) { prompt_send_response("Unable to get Ble Log level"); } else { prompt_send_response_fmt(buffer, 32, "Ble Log level: %d", log_level); } } // ARG: // 0 - Request BLE firmware to coredump // 1 - Force BLE firmware to hard fault // 2 - Force the BLE chip to watchdog (by wedging a task) void command_ble_core_dump(const char *command) { int option = atoi(command); if ((option < 0) || (option >= BtleCoreDumpCount)) { prompt_send_response("Invalid BLE core command"); return; } bt_driver_core_dump(option); } #if PERFORMANCE_TESTS // for task_watchdog_bit_set_all #include "drivers/task_watchdog.h" // For taskYIELD() #include "FreeRTOS.h" #include "task.h" // Average this many iterations of the text test for getting useful perf numbers. #define PERFTEST_TEXT_ITERATIONS 5 static GContext s_perftest_ctx = {}; static GContext *prv_perftest_get_context(void) { GContext *ctx = &s_perftest_ctx; FrameBuffer *fb = compositor_get_framebuffer(); memset(fb->buffer, 0xff, FRAMEBUFFER_SIZE_BYTES); graph
(s_sleep_test_timer, 31, prv_sleep_timer_test_cb, (void *)(uintptr_t)count, 0)
<|repo_name|>pebble <|file_sep|>src/fw/console/prompt_commands.c <|fim_prefix|> than 5% bool passed = ((duration_us >= i) && (duration_us <= ((i * 105) / 100))); if (!passed) { prompt_send_response_fmt(buf, sizeof(buf), "Audit Failed: Expected %"PRIu32", Got %"PRIu32, i, duration_us); } } prompt_send_response("delay_us audit complete"); __enable_irq(); } // Simply parks the chip permanently in stop mode in whatever state it's currently in. This can be // pretty handy when trying to profile power of the chip under certains states // NOTE: If you did not configure with `--nowatchdog`, the HW watchdog will reboot you in ~8s void command_enter_stop(void) { dbgserial_putstr("Entering stop mode indefinitely ... reboot your board to get out!!"); __disable_irq(); RTC_ITConfig(RTC_IT_WUT, DISABLE); RTC_WakeUpCmd(DISABLE); // disable all IRQn_Type >= 0 interrupts for (size_t i = 0; i < ARRAY_LENGTH(NVIC->ISER); i++) { NVIC->ICER[i] = NVIC->ISER[i]; } // disable SysTick SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; enter_stop_mode(); dbgserial_putstr("woah, failed to enter stop mode"); while (1) { } } #ifndef RECOVERY_FW // Create a bunch of fragmentation in the filesystem by creating a large number // of small files and only deleting a small number of them void command_litter_filesystem(void) { char name[10]; for (int i = 0; i < 100; i++) { snprintf(name, sizeof(name), "litter%d", i); int fd = pfs_open(name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 300); if (i % 5 == 0) { pfs_close_and_remove(fd); } else { pfs_close(fd); } } } #endif #endif static GAPLEConnection *prv_get_le_connection_and_print_info(void) { GAPLEConnection *conn = gap_le_connection_any(); if (!conn) { prompt_send_response("No device connected"); } else { char buf[80]; prompt_send_response_fmt(buf, sizeof(buf), "Connected to " BT_DEVICE_ADDRESS_FMT, BT_DEVICE_ADDRESS_XPLODE(conn->device.address)); } return conn; } void command_bt_conn_param_set( char *interval_min_1_25ms, char *interval_max_1_25ms, char *slave_latency_events, char *timeout_10ms) { BleConnectionParamsUpdateReq req = { .interval_min_1_25ms = atoi(interval_min_1_25ms), .interval_max_1_25ms = atoi(interval_max_1_25ms), .slave_latency_events = atoi(slave_latency_events), .supervision_timeout_10ms = atoi(timeout_10ms), }; GAPLEConnection *conn = prv_get_le_connection_and_print_info(); BTDeviceInternal addr = {}; if (conn) { addr.address = conn->device.address; } bt_driver_le_connection_parameter_update(&addr, &req); } // Not in a header because it's really only used from within the gatt_service_changed module extern void gatt_client_discovery_discover_range( GAPLEConnection *connection, ATTHandleRange *hdl_range); void command_bt_disc_start(char *start_handle, char *end_handle) { bt_lock(); { ATTHandleRange range = { .start = atoi(start_handle), .end = atoi(end_handle) }; GAPLEConnection *conn = prv_get_le_connection_and_print_info(); if (conn) { gatt_client_discovery_discover_range(conn, &range); } } bt_unlock(); } void command_bt_disc_stop(void) { bt_lock(); { GAPLEConnection *conn = prv_get_le_connection_and_print_info(); if (conn) { bt_driver_gatt_stop_discovery(conn); } } bt_unlock(); } #if BT_CONTROLLER_DA14681 static TimerID s_sleep_test_timer = TIMER_INVALID_ID; static uint32_t s_num_sleep_iters = 0; static void prv_sleep_timer_test_cb(void *data) { uint32_t count = (uint32_t)data; for (int j = 0; j < 10; j++) { bt_driver_send_sleep_test_cmd(true); psleep(9); } if (count >= s_num_sleep_iters) { bt_driver_send_sleep_test_cmd(false); prompt_send_response("100 % - PASS"); new_timer_delete(s_sleep_test_timer); prompt_command_finish(); } else { char buf[80]; prompt_send_response_fmt(buf, sizeof(buf), "%d %%", (int)((count * 100) / s_num_sleep_iters)); count++; new_timer_start<|fim_suffix|>; } } // Attempts to check that the Dialog chip sleep mode is working correctly by forcing wakeups at // different times. (See PBL-39777). The timeouts delays may seem a little random but I found with // this combo of values I was able to hit the issue on both failing units I have pretty quickly. extern bool bt_test_chip_in_test_mode(void); void command_bt_sleep_check(const char *iters) { s_num_sleep_iters = atoi(iters); // It seems like advertising while doing this makes the issue more likely to happen // (I suspect because there are even more enters/exits from sleep happening) if (bt_test_chip_in_test_mode()) { prompt_send_response("You must run \"bt test stop\" to conduct sleep test!"); return; } prompt_send_response("Starting BT sleep check test"); s_sleep_test_timer = new_timer_create(); new_timer_start(s_sleep_test_timer , 10, prv_sleep_timer_test_cb, (void *)(uintptr_t)0, 0); prompt_command_continues_after_returning(); } void command_btle_unmod_tx_start(char *tx_channel) { bt_driver_start_unmodulated_tx(atoi(tx_channel)); } void command_btle_unmod_tx_stop(void) { bt_driver_stop_unmodulated_tx(); } void command_btle_test_le_tx_start( char *tx_channel, char *tx_packet_length, char *packet_payload_type) { bt_driver_le_transmitter_test( atoi(tx_channel), atoi(tx_packet_length), atoi(packet_payload_type)); } void command_btle_test_rx_start(char *rx_channel) { bt_driver_le_receiver_test(atoi(rx_channel)); } void command_btle_test_end(void) { bt_driver_le_test_end(); } //# if PLATFORM_ROBERT static const char *s_btle_pa_config_strings[3] = { "disable", "enable", "bypass" }; void command_btle_pa_set(char *command) { char buffer[64]; int index; for (index = 0; index < BtlePaConfigCount; ++index) { if (strcmp(command, s_btle_pa_config_strings[index]) == 0) { break; } } if (index >= BtlePaConfigCount) { prompt_send_response_fmt(buffer, sizeof(buffer), "BTLE PA options are: %s, %s, %s", s_btle_pa_config_strings[BtlePaConfig_Disable], s_btle_pa_config_strings[BtlePaConfig_Enable], s_btle_pa_config_strings[BtlePaConfig_Bypass]); } else { bt_driver_le_test_pa(index); prompt_send_response_fmt(buffer, sizeof(buffer), "BTLE PA set to: %s", s_btle_pa_config_strings[index]); } } //# endif #endif extern void hc_endpoint_logging_set_level(uint8_t level); void command_ble_logging_set_level(const char *level) { char buffer[32]; int log_level = atoi(level); if (log_level < 0) { log_level = 0; } else if (log_level > 255) { log_level = 255; } hc_endpoint_logging_set_level(log_level); prompt_send_response_fmt(buffer, 32, "Ble Log level set to: %i", log_level); } extern bool hc_endpoint_logging_get_level(uint8_t *level); void command_ble_logging_get_level(void) { uint8_t log_level; char buffer[32]; if (!hc_endpoint_logging_get_level(&log_level)) { prompt_send_response("Unable to get Ble Log level"); } else { prompt_send_response_fmt(buffer, 32, "Ble Log level: %d", log_level); } } // ARG: // 0 - Request BLE firmware to coredump // 1 - Force BLE firmware to hard fault // 2 - Force the BLE chip to watchdog (by wedging a task) void command_ble_core_dump(const char *command) { int option = atoi(command); if ((option < 0) || (option >= BtleCoreDumpCount)) { prompt_send_response("Invalid BLE core command"); return; } bt_driver_core_dump(option); } #if PERFORMANCE_TESTS // for task_watchdog_bit_set_all #include "drivers/task_watchdog.h" // For taskYIELD() #include "FreeRTOS.h" #include "task.h" // Average this many iterations of the text test for getting useful perf numbers. #define PERFTEST_TEXT_ITERATIONS 5 static GContext s_perftest_ctx = {}; static GContext *prv_perftest_get_context(void) { GContext *ctx = &s_perftest_ctx; FrameBuffer *fb = compositor_get_framebuffer(); memset(fb->buffer, 0xff, FRAMEBUFFER_SIZE_BYTES); graph<|fim_middle|>(s_sleep_test_timer, 31, prv_sleep_timer_test_cb, (void *)(uintptr_t)count, 0)<|endoftext|>
masked_node
compound_statement
platform/silk/boot/src/main.c
ph_TIM6 | RCC_APB1Periph_TIM7 | RCC_APB1Periph_TIM12 | RCC_APB1Periph_TIM13 | RCC_APB1Periph_TIM14 | RCC_APB1Periph_WWDG | RCC_APB1Periph_SPI2 | RCC_APB1Periph_SPI3 | RCC_APB1Periph_USART2 | RCC_APB1Periph_USART3 | RCC_APB1Periph_UART4 | RCC_APB1Periph_UART5 | RCC_APB1Periph_I2C1 | RCC_APB1Periph_I2C2 | RCC_APB1Periph_I2C3 | RCC_APB1Periph_CAN1 | RCC_APB1Periph_CAN2 | RCC_APB1Periph_PWR | RCC_APB1Periph_DAC | RCC_APB1Periph_UART7 | RCC_APB1Periph_UART8; const uint32_t apb2_periphs = RCC_APB2Periph_TIM1 | RCC_APB2Periph_TIM8 | RCC_APB2Periph_USART1 | RCC_APB2Periph_USART6 | RCC_APB2Periph_ADC | RCC_APB2Periph_ADC1 | RCC_APB2Periph_ADC2 | RCC_APB2Periph_ADC3 | RCC_APB2Periph_SDIO | RCC_APB2Periph_SPI1 | RCC_APB2Periph_SPI4 | RCC_APB2Periph_SYSCFG | RCC_APB2Periph_TIM9 | RCC_APB2Periph_TIM10 | RCC_APB2Periph_TIM11 | RCC_APB2Periph_SPI5 | RCC_APB2Periph_SPI6 | RCC_APB2Periph_SAI1 | RCC_APB2Periph_LTDC; RCC_DeInit(); RCC_AHB1PeriphResetCmd(ahb1_periphs, ENABLE); RCC_AHB1PeriphResetCmd(ahb1_periphs, DISABLE); RCC_AHB2PeriphResetCmd(ahb2_periphs, ENABLE); RCC_AHB2PeriphResetCmd(ahb2_periphs, DISABLE); RCC_AHB3PeriphResetCmd(ahb3_periphs, ENABLE); RCC_AHB3PeriphResetCmd(ahb3_periphs, DISABLE); RCC_APB1PeriphResetCmd(apb1_periphs, ENABLE); RCC_APB1PeriphResetCmd(apb1_periphs, DISABLE); RCC_APB2PeriphResetCmd(apb2_periphs, ENABLE); RCC_APB2PeriphResetCmd(apb2_periphs, DISABLE); // The Cortex-M user guide states that the reset values for the core registers // are as follows: // R0-R12 = Unknown // MSP = VECTOR_TABLE[0] (main stack pointer) // PSP = Unknown (process stack pointer) // LR = 0xFFFFFFFF // PC = VECTOR_TABLE[1] // PRIMASK = 0x0 // FAULTMASK = 0x0 // BASEPRI = 0x0 // CONTROL = 0x0 // // Attempt to put the processor into as close to the reset state as possible // before passing control to the firmware. // // No attempt is made to set CONTROL to zero as it should already be set to // the reset value when this code executes. __asm volatile ( "cpsie if\n" // Clear PRIMASK and FAULTMASK "mov lr, 0xFFFFFFFF\n" "mov sp, %[initial_sp]\n" "bx %[reset_handler]\n" : : [initial_sp] "r" (initial_stack_pointer), [reset_handler] "r" (reset_handler) ); __builtin_unreachable(); } static bool check_and_increment_reset_loop_detection_bits(void) { uint8_t counter = (boot_bit_test(BOOT_BIT_RESET_LOOP_DETECT_THREE) << 2) | (boot_bit_test(BOOT_BIT_RESET_LOOP_DETECT_TWO) << 1) | boot_bit_test(BOOT_BIT_RESET_LOOP_DETECT_ONE); if (counter == 7) { boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_ONE); boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_TWO); boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_THREE); return true; } switch (++counter) { case 1: boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_ONE); break; case 2: boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_ONE); boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_TWO); break; case 3: boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_ONE); break; case 4: boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_ONE); boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_TWO); boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_THREE); break; case 5: boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_ONE); break; case 6: boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_ONE); boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_TWO); break; case 7: boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_ONE); break; default: PBL_CROAK("reset loop boot bits overrun"); break; } return false; } static bool check_for_recovery_start_failure() { return boot_bit_test(BOOT_BIT_RECOVERY_START_IN_PROGRESS); } static bool check_for_fw_start_failure() { // Add more failure conditions here. if (!watchdog_check_reset_flag() && !boot_bit_test(BOOT_BIT_SOFTWARE_FAILURE_OCCURRED))
// We failed to start our firmware successfully! if (watchdog_check_reset_flag()) { dbgserial_putstr("Watchdog caused a reset"); } if (boot_bit_test(BOOT_BIT_SOFTWARE_FAILURE_OCCURRED)) { dbgserial_putstr("Software failure caused a reset"); } // Clean up after the last failure. boot_bit_clear(BOOT_BIT_SOFTWARE_FAILURE_OCCURRED); // We have a "three strikes" algorithm: if the watch fails three times, return true // to tell the parent we should load the recovery firmware. A reset for any other reason // will reset this algorithm. if (boot_bit_test(BOOT_BIT_FW_START_FAIL_STRIKE_TWO)) { // Yikes, our firmware is screwed. Boot into recovery mode. dbgserial_putstr("Failed to start firmware, strike three."); boot_bit_clear(BOOT_BIT_FW_START_FAIL_STRIKE_ONE); boot_bit_clear(BOOT_BIT_FW_START_FAIL_STRIKE_TWO); return true; } else if (boot_bit_test(BOOT_BIT_FW_START_FAIL_STRIKE_ONE)) { dbgserial_putstr("Failed to start firmware, strike two."); boot_bit_set(BOOT_BIT_FW_START_FAIL_STRIKE_TWO); } else { dbgserial_putstr("Failed to start firmware, strike one."); boot_bit_set(BOOT_BIT_FW_START_FAIL_STRIKE_ONE); } return false; } static bool prv_prf_button_combination_is_pressed(void) { return (button_is_pressed(BUTTON_ID_UP) && button_is_pressed(BUTTON_ID_BACK) && button_is_pressed(BUTTON_ID_SELECT) && !button_is_pressed(BUTTON_ID_DOWN)); } static bool check_force_boot_recovery(void) { if (boot_bit_test(BOOT_BIT_FORCE_PRF)) { boot_bit_clear(BOOT_BIT_FORCE_PRF); return true; } if (prv_prf_button_combination_is_pressed()) { dbgserial_putstr("Hold down UP + BACK + SELECT for 5 secs. to force-boot PRF"); for (int i = 0; i < 5000; ++i) { if (!prv_prf_button_combination_is_pressed()) { // stop waiting if not held down any longer return false; } delay_ms(1); } return true; } void *reset_vector, *initial_sp; prv_get_fw_reset_vector(&reset_vector, &initial_sp); if ((uintptr_t)reset_vector == 0xffffffff || (uintptr_t)initial_sp == 0xffffffff) { dbgserial_putstr("Firmware is erased"); return true; } return false; } static void sad_watch(uint32_t error_code) { dbgserial_putstr("SAD WATCH"); char error_code_buffer[12]; itoa_hex(error_code, error_code_buffer, sizeof(error_code_buffer)); dbgserial_putstr(error_code_buffer); display_error_code(error_code); static uint8_t prev_button_state = 0; prev_button_state = button_get_state_bits() & ~SELECT_BUTTON_MASK; while (1) { // See if we should restart uint8_t button_state = button_get_state_bits() & ~SELECT_BUTTON_MASK; if (button_state != prev_button_state) { system_reset(); } delay_ms(10); } } static void check_and_handle_resuming_from_standby(void) { periph_config_enable(RCC_APB1PeriphClockCmd, RCC_APB1Periph_PWR); if (PWR_GetFlagStatus(PWR_FLAG_SB) == SET) { // We just woke up from standby. For some reason this leaves the system in a funny state, // so clear the flag and reboot again to really clear things up. PWR_ClearFlag(PWR_FLAG_SB); dbgserial_putstr("exit standby"); system_hard_reset(); } periph_config_disable(RCC_APB1PeriphClockCmd, RCC_APB1Periph_PWR); } void boot_main(void) { gpio_enable_all(); check_and_handle_resuming_from_standby(); dbgserial_init(); dbgserial_putstr(""); dbgserial_putstr(" ___ _ _ _ "); dbgserial_putstr("/ __><_>| || |__"); dbgserial_putstr("\\__ \\| || || / /"); dbgserial_putstr("<___/|_||_||_\\_\\"); dbgserial_putstr(""); // PMIC requires I2C i2c_init(); dbgserial_putstr("i2c inited"); pmic_init(); dbgserial_putstr("pmic inited"); boot_bit_init(); dbgserial_putstr("boot bit"); boot_version_write(); // Write the bootloader version to serial-out { char bootloader_version_str[12]; memset(bootloader_version_str, 0, 12); itoa_hex(
{ // We're good, we're just starting normally. PBL_LOG_VERBOSE("We're good, we're just starting normally."); boot_bit_clear(BOOT_BIT_FW_START_FAIL_STRIKE_ONE); boot_bit_clear(BOOT_BIT_FW_START_FAIL_STRIKE_TWO); return false; }
<|repo_name|>pebble <|file_sep|>platform/silk/boot/src/main.c <|fim_prefix|>ph_TIM6 | RCC_APB1Periph_TIM7 | RCC_APB1Periph_TIM12 | RCC_APB1Periph_TIM13 | RCC_APB1Periph_TIM14 | RCC_APB1Periph_WWDG | RCC_APB1Periph_SPI2 | RCC_APB1Periph_SPI3 | RCC_APB1Periph_USART2 | RCC_APB1Periph_USART3 | RCC_APB1Periph_UART4 | RCC_APB1Periph_UART5 | RCC_APB1Periph_I2C1 | RCC_APB1Periph_I2C2 | RCC_APB1Periph_I2C3 | RCC_APB1Periph_CAN1 | RCC_APB1Periph_CAN2 | RCC_APB1Periph_PWR | RCC_APB1Periph_DAC | RCC_APB1Periph_UART7 | RCC_APB1Periph_UART8; const uint32_t apb2_periphs = RCC_APB2Periph_TIM1 | RCC_APB2Periph_TIM8 | RCC_APB2Periph_USART1 | RCC_APB2Periph_USART6 | RCC_APB2Periph_ADC | RCC_APB2Periph_ADC1 | RCC_APB2Periph_ADC2 | RCC_APB2Periph_ADC3 | RCC_APB2Periph_SDIO | RCC_APB2Periph_SPI1 | RCC_APB2Periph_SPI4 | RCC_APB2Periph_SYSCFG | RCC_APB2Periph_TIM9 | RCC_APB2Periph_TIM10 | RCC_APB2Periph_TIM11 | RCC_APB2Periph_SPI5 | RCC_APB2Periph_SPI6 | RCC_APB2Periph_SAI1 | RCC_APB2Periph_LTDC; RCC_DeInit(); RCC_AHB1PeriphResetCmd(ahb1_periphs, ENABLE); RCC_AHB1PeriphResetCmd(ahb1_periphs, DISABLE); RCC_AHB2PeriphResetCmd(ahb2_periphs, ENABLE); RCC_AHB2PeriphResetCmd(ahb2_periphs, DISABLE); RCC_AHB3PeriphResetCmd(ahb3_periphs, ENABLE); RCC_AHB3PeriphResetCmd(ahb3_periphs, DISABLE); RCC_APB1PeriphResetCmd(apb1_periphs, ENABLE); RCC_APB1PeriphResetCmd(apb1_periphs, DISABLE); RCC_APB2PeriphResetCmd(apb2_periphs, ENABLE); RCC_APB2PeriphResetCmd(apb2_periphs, DISABLE); // The Cortex-M user guide states that the reset values for the core registers // are as follows: // R0-R12 = Unknown // MSP = VECTOR_TABLE[0] (main stack pointer) // PSP = Unknown (process stack pointer) // LR = 0xFFFFFFFF // PC = VECTOR_TABLE[1] // PRIMASK = 0x0 // FAULTMASK = 0x0 // BASEPRI = 0x0 // CONTROL = 0x0 // // Attempt to put the processor into as close to the reset state as possible // before passing control to the firmware. // // No attempt is made to set CONTROL to zero as it should already be set to // the reset value when this code executes. __asm volatile ( "cpsie if\n" // Clear PRIMASK and FAULTMASK "mov lr, 0xFFFFFFFF\n" "mov sp, %[initial_sp]\n" "bx %[reset_handler]\n" : : [initial_sp] "r" (initial_stack_pointer), [reset_handler] "r" (reset_handler) ); __builtin_unreachable(); } static bool check_and_increment_reset_loop_detection_bits(void) { uint8_t counter = (boot_bit_test(BOOT_BIT_RESET_LOOP_DETECT_THREE) << 2) | (boot_bit_test(BOOT_BIT_RESET_LOOP_DETECT_TWO) << 1) | boot_bit_test(BOOT_BIT_RESET_LOOP_DETECT_ONE); if (counter == 7) { boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_ONE); boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_TWO); boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_THREE); return true; } switch (++counter) { case 1: boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_ONE); break; case 2: boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_ONE); boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_TWO); break; case 3: boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_ONE); break; case 4: boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_ONE); boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_TWO); boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_THREE); break; case 5: boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_ONE); break; case 6: boot_bit_clear(BOOT_BIT_RESET_LOOP_DETECT_ONE); boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_TWO); break; case 7: boot_bit_set(BOOT_BIT_RESET_LOOP_DETECT_ONE); break; default: PBL_CROAK("reset loop boot bits overrun"); break; } return false; } static bool check_for_recovery_start_failure() { return boot_bit_test(BOOT_BIT_RECOVERY_START_IN_PROGRESS); } static bool check_for_fw_start_failure() { // Add more failure conditions here. if (!watchdog_check_reset_flag() && !boot_bit_test(BOOT_BIT_SOFTWARE_FAILURE_OCCURRED)) <|fim_suffix|> // We failed to start our firmware successfully! if (watchdog_check_reset_flag()) { dbgserial_putstr("Watchdog caused a reset"); } if (boot_bit_test(BOOT_BIT_SOFTWARE_FAILURE_OCCURRED)) { dbgserial_putstr("Software failure caused a reset"); } // Clean up after the last failure. boot_bit_clear(BOOT_BIT_SOFTWARE_FAILURE_OCCURRED); // We have a "three strikes" algorithm: if the watch fails three times, return true // to tell the parent we should load the recovery firmware. A reset for any other reason // will reset this algorithm. if (boot_bit_test(BOOT_BIT_FW_START_FAIL_STRIKE_TWO)) { // Yikes, our firmware is screwed. Boot into recovery mode. dbgserial_putstr("Failed to start firmware, strike three."); boot_bit_clear(BOOT_BIT_FW_START_FAIL_STRIKE_ONE); boot_bit_clear(BOOT_BIT_FW_START_FAIL_STRIKE_TWO); return true; } else if (boot_bit_test(BOOT_BIT_FW_START_FAIL_STRIKE_ONE)) { dbgserial_putstr("Failed to start firmware, strike two."); boot_bit_set(BOOT_BIT_FW_START_FAIL_STRIKE_TWO); } else { dbgserial_putstr("Failed to start firmware, strike one."); boot_bit_set(BOOT_BIT_FW_START_FAIL_STRIKE_ONE); } return false; } static bool prv_prf_button_combination_is_pressed(void) { return (button_is_pressed(BUTTON_ID_UP) && button_is_pressed(BUTTON_ID_BACK) && button_is_pressed(BUTTON_ID_SELECT) && !button_is_pressed(BUTTON_ID_DOWN)); } static bool check_force_boot_recovery(void) { if (boot_bit_test(BOOT_BIT_FORCE_PRF)) { boot_bit_clear(BOOT_BIT_FORCE_PRF); return true; } if (prv_prf_button_combination_is_pressed()) { dbgserial_putstr("Hold down UP + BACK + SELECT for 5 secs. to force-boot PRF"); for (int i = 0; i < 5000; ++i) { if (!prv_prf_button_combination_is_pressed()) { // stop waiting if not held down any longer return false; } delay_ms(1); } return true; } void *reset_vector, *initial_sp; prv_get_fw_reset_vector(&reset_vector, &initial_sp); if ((uintptr_t)reset_vector == 0xffffffff || (uintptr_t)initial_sp == 0xffffffff) { dbgserial_putstr("Firmware is erased"); return true; } return false; } static void sad_watch(uint32_t error_code) { dbgserial_putstr("SAD WATCH"); char error_code_buffer[12]; itoa_hex(error_code, error_code_buffer, sizeof(error_code_buffer)); dbgserial_putstr(error_code_buffer); display_error_code(error_code); static uint8_t prev_button_state = 0; prev_button_state = button_get_state_bits() & ~SELECT_BUTTON_MASK; while (1) { // See if we should restart uint8_t button_state = button_get_state_bits() & ~SELECT_BUTTON_MASK; if (button_state != prev_button_state) { system_reset(); } delay_ms(10); } } static void check_and_handle_resuming_from_standby(void) { periph_config_enable(RCC_APB1PeriphClockCmd, RCC_APB1Periph_PWR); if (PWR_GetFlagStatus(PWR_FLAG_SB) == SET) { // We just woke up from standby. For some reason this leaves the system in a funny state, // so clear the flag and reboot again to really clear things up. PWR_ClearFlag(PWR_FLAG_SB); dbgserial_putstr("exit standby"); system_hard_reset(); } periph_config_disable(RCC_APB1PeriphClockCmd, RCC_APB1Periph_PWR); } void boot_main(void) { gpio_enable_all(); check_and_handle_resuming_from_standby(); dbgserial_init(); dbgserial_putstr(""); dbgserial_putstr(" ___ _ _ _ "); dbgserial_putstr("/ __><_>| || |__"); dbgserial_putstr("\\__ \\| || || / /"); dbgserial_putstr("<___/|_||_||_\\_\\"); dbgserial_putstr(""); // PMIC requires I2C i2c_init(); dbgserial_putstr("i2c inited"); pmic_init(); dbgserial_putstr("pmic inited"); boot_bit_init(); dbgserial_putstr("boot bit"); boot_version_write(); // Write the bootloader version to serial-out { char bootloader_version_str[12]; memset(bootloader_version_str, 0, 12); itoa_hex(<|fim_middle|>{ // We're good, we're just starting normally. PBL_LOG_VERBOSE("We're good, we're just starting normally."); boot_bit_clear(BOOT_BIT_FW_START_FAIL_STRIKE_ONE); boot_bit_clear(BOOT_BIT_FW_START_FAIL_STRIKE_TWO); return false; }<|endoftext|>
masked_node
argument_list
tests/fw/applib/test_app_outbox.c
_handler, s_expected_cb_ctx)); assert_syscall_failed(); } void test_app_outbox__send_but_consumer_not_registered(void) { prv_register(); app_outbox_service_unregister(AppOutboxServiceTagUnitTest); app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); assert_sent_cb_last_status(AppOutboxStatusConsumerDoesNotExist); } void test_app_outbox__send_but_max_pending_messages_reached(void) { prv_register(); uint32_t max_pending_messages = app_outbox_service_max_pending_messages(AppOutboxServiceTagUnitTest); for (uint32_t i = 0; i < max_pending_messages; ++i) { app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); cl_assert_equal_i(s_num_sent_handler_called, 0); } app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); assert_sent_cb_last_status(AppOutboxStatusOutOfResources); } void test_app_outbox__send_but_oom(void) { prv_register(); fake_kernel_malloc_set_largest_free_block(0); app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); assert_sent_cb_last_status(AppOutboxStatusOutOfMemory); } void test_app_outbox__send_but_null_sent_handler(void) { prv_register(); // Invalid data, so normally an event would get put to invoke the sent_handler, // but sent handler is NULL. Expect no events to be put. cl_assert_passert(app_outbox_send(NULL, 0, NULL, s_expected_cb_ctx)); cl_assert_equal_i(s_num_app_outbox_events_sent, 0); } void test_app_outbox__send(void) { fake_kernel_malloc_mark(); prv_register(); uint32_t max_pending_messages = app_outbox_service_max_pending_messages(AppOutboxServiceTagUnitTest); AppOutboxMessage *message[max_pending_messages]; for (uint32_t i = 0; i < max_pending_messages; ++i) { app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); cl_assert_equal_i(s_num_app_outbox_events_sent, 0); cl_assert_equal_i(s_num_message_handler_calls, i + 1); cl_assert(s_last_message); cl_assert_equal_p(s_test_data, s_last_message->data); cl_assert_equal_i(s_test_data_length, s_last_message->length); cl_assert_equal_b(false, app_outbox_service_is_message_cancelled(s_last_message)); message[i] = s_last_message; } for (uint32_t i = 0; i < max_pending_messages; ++i) { app_outbox_service_consume_message(message[i], AppOutboxStatusSuccess); cl_assert_equal_i(s_num_app_outbox_events_sent, i + 1); assert_sent_cb_last_status(AppOutboxStatusSuccess); } fake_kernel_malloc_mark_assert_equal(); } void test_app_outbox__unregister_with_pending_message(void) { fake_kernel_malloc_mark(); prv_register(); app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); cl_assert(s_last_message); app_outbox_service_unregister(AppOutboxServiceTagUnitTest); cl_assert_equal_i(s_num_app_outbox_events_sent, 1); assert_sent_cb_last_status(AppOutboxStatusConsumerDoesNotExist); cl_assert_equal_b(true, app_outbox_service_is_message_cancelled(s_last_message)); // the consumer must call ..._consume_message(), to free the resources: app_outbox_service_consume_message(s_last_message, AppOutboxStatusSuccess); // sent_handler shouldn't get called again, it's already been called: cl_assert_equal_i(s_num_app_outbox_events_sent, 1); fake_kernel_malloc_mark_assert_equal(); } void test_app_outbox__cleanup_all_with_pending_message(void) { fake_kernel_malloc_mark(); prv_register(); app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); cl_assert(s_last_message); app_outbox_service_cleanup_all_pending_messages(); // sent_handler shouldn't get called when cleaning up: cl_assert_equal_i(s_num_app_outbox_events_sent, 0); cl_assert_equal_b
; // the consumer must call ..._consume_message(), to free the resources: app_outbox_service_consume_message(s_last_message, AppOutboxStatusSuccess); fake_kernel_malloc_mark_assert_equal(); }
(true, app_outbox_service_is_message_cancelled(s_last_message))
<|repo_name|>pebble <|file_sep|>tests/fw/applib/test_app_outbox.c <|fim_prefix|>_handler, s_expected_cb_ctx)); assert_syscall_failed(); } void test_app_outbox__send_but_consumer_not_registered(void) { prv_register(); app_outbox_service_unregister(AppOutboxServiceTagUnitTest); app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); assert_sent_cb_last_status(AppOutboxStatusConsumerDoesNotExist); } void test_app_outbox__send_but_max_pending_messages_reached(void) { prv_register(); uint32_t max_pending_messages = app_outbox_service_max_pending_messages(AppOutboxServiceTagUnitTest); for (uint32_t i = 0; i < max_pending_messages; ++i) { app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); cl_assert_equal_i(s_num_sent_handler_called, 0); } app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); assert_sent_cb_last_status(AppOutboxStatusOutOfResources); } void test_app_outbox__send_but_oom(void) { prv_register(); fake_kernel_malloc_set_largest_free_block(0); app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); assert_sent_cb_last_status(AppOutboxStatusOutOfMemory); } void test_app_outbox__send_but_null_sent_handler(void) { prv_register(); // Invalid data, so normally an event would get put to invoke the sent_handler, // but sent handler is NULL. Expect no events to be put. cl_assert_passert(app_outbox_send(NULL, 0, NULL, s_expected_cb_ctx)); cl_assert_equal_i(s_num_app_outbox_events_sent, 0); } void test_app_outbox__send(void) { fake_kernel_malloc_mark(); prv_register(); uint32_t max_pending_messages = app_outbox_service_max_pending_messages(AppOutboxServiceTagUnitTest); AppOutboxMessage *message[max_pending_messages]; for (uint32_t i = 0; i < max_pending_messages; ++i) { app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); cl_assert_equal_i(s_num_app_outbox_events_sent, 0); cl_assert_equal_i(s_num_message_handler_calls, i + 1); cl_assert(s_last_message); cl_assert_equal_p(s_test_data, s_last_message->data); cl_assert_equal_i(s_test_data_length, s_last_message->length); cl_assert_equal_b(false, app_outbox_service_is_message_cancelled(s_last_message)); message[i] = s_last_message; } for (uint32_t i = 0; i < max_pending_messages; ++i) { app_outbox_service_consume_message(message[i], AppOutboxStatusSuccess); cl_assert_equal_i(s_num_app_outbox_events_sent, i + 1); assert_sent_cb_last_status(AppOutboxStatusSuccess); } fake_kernel_malloc_mark_assert_equal(); } void test_app_outbox__unregister_with_pending_message(void) { fake_kernel_malloc_mark(); prv_register(); app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); cl_assert(s_last_message); app_outbox_service_unregister(AppOutboxServiceTagUnitTest); cl_assert_equal_i(s_num_app_outbox_events_sent, 1); assert_sent_cb_last_status(AppOutboxStatusConsumerDoesNotExist); cl_assert_equal_b(true, app_outbox_service_is_message_cancelled(s_last_message)); // the consumer must call ..._consume_message(), to free the resources: app_outbox_service_consume_message(s_last_message, AppOutboxStatusSuccess); // sent_handler shouldn't get called again, it's already been called: cl_assert_equal_i(s_num_app_outbox_events_sent, 1); fake_kernel_malloc_mark_assert_equal(); } void test_app_outbox__cleanup_all_with_pending_message(void) { fake_kernel_malloc_mark(); prv_register(); app_outbox_send(s_test_data, s_test_data_length, test_app_outbox_sent_handler, s_expected_cb_ctx); cl_assert(s_last_message); app_outbox_service_cleanup_all_pending_messages(); // sent_handler shouldn't get called when cleaning up: cl_assert_equal_i(s_num_app_outbox_events_sent, 0); cl_assert_equal_b<|fim_suffix|>; // the consumer must call ..._consume_message(), to free the resources: app_outbox_service_consume_message(s_last_message, AppOutboxStatusSuccess); fake_kernel_malloc_mark_assert_equal(); } <|fim_middle|>(true, app_outbox_service_is_message_cancelled(s_last_message))<|endoftext|>
masked_node
argument_list
src/fw/apps/system_apps/launcher/default/launcher_app_glance_watchfaces.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "launcher_app_glance_watchfaces.h" #include "launcher_app_glance_structured.h" #include "kernel/events.h" #include "kernel/pbl_malloc.h" #include "process_management/app_install_manager.h" #include "shell/normal/watchface.h" #include "system/passert.h" #include "util/attributes.h" #include "util/string.h" #include "util/struct.h" #include <stdio.h> typedef struct LauncherAppGlanceWatchfaces { char title[APP_NAME_SIZE_BYTES]; char subtitle[APP_NAME_SIZE_BYTES]; KinoReel *icon; } LauncherAppGlanceWatchfaces; static KinoReel *prv_get_icon(LauncherAppGlanceStructured *structured_glance) { LauncherAppGlanceWatchfaces *watchfaces_glance = launcher_app_glance_structured_get_data(structured_glance); return NULL_SAFE_FIELD_ACCESS(watchfaces_glance, icon, NULL); } static const char *prv_get_title(LauncherAppGlanceStructured *structured_glance) { LauncherAppGlanceWatchfaces *watchfaces_glance = launcher_app_glance_structured_get_data(structured_glance); return NULL_SAFE_FIELD_ACCESS(watchfaces_glance, title, NULL); } static void prv_watchfaces_glance_subtitle_dynamic_text_node_update( UNUSED GContext *ctx, UNUSED GTextNode *node, UNUSED const GRect *box, UNUSED const GTextNodeDrawConfig *config, UNUSED bool render, char *buffer, size_t buffer_size, void *user_data) { LauncherAppGlanceStructured *structured_glance = user_data; LauncherAppGlanceWatchfaces *watchfaces_glance = launcher_app_glance_structured_get_data(structured_glance); if (watchfaces_glance) { strncpy(buffer, watchfaces_glance->subtitle, buffer_size); buffer[buffer_size - 1] = '\0'; } } static GTextNode *prv_create_subtitle_node(LauncherAppGlanceStructured *structured_glance) { return launcher_app_glance_structured_create_subtitle_text_node( structured_glance, prv_watchfaces_glance_subtitle_dynamic_text_node_update); } static void prv_destructor(LauncherAppGlanceStructured *structured_glance) { LauncherAppGlanceWatchfaces *watchfaces_glance = launcher_app_glance_structured_get_data(structured_glance); if (watchfaces_glance) { kino_reel_destroy(watchfaces_glance->icon); } app_free(watchfaces_glance); } static void prv_update_active_watchface_title(LauncherAppGlanceWatchfaces *watchfaces_glance) { const AppInstallId selected_watch_id = watchface_get_default_install_id(); AppInstallEntry entry; if (app_install_get_entry_for_install_id(selected_watch_id, &entry)) { const size_t watchfaces_subtitle_size = sizeof(watchfaces_glance->subtitle); strncpy(watchfaces_glance->subtitle, entry.name, watchfaces_subtitle_size); watchfaces_glance->subtitle[watchfaces_subtitle_size - 1] = '\0'; } } static const LauncherAppGlanceStructuredImpl s_watchfaces_structured_glance_impl = { .get_icon = prv_get_icon, .get_title = prv_get_title, .create_subtitle_node = prv_create_subtitle_node, .destructor = prv_destructor, }; LauncherAppGlance *launcher_app_glance_watchfaces_create(const AppMenuNode *node) { PBL_ASSERTN(node); LauncherAppGlanceWatchfaces *watchfaces_glance = app_zalloc_check(sizeof(*watchfaces_glance)); // Copy the name of the Watchfaces app as the title const size_t title_size = sizeof(watchfaces_glance->title); strncpy
; watchfaces_glance->title[title_size - 1] = '\0'; // Create the icon for the Watchfaces app watchfaces_glance->icon = kino_reel_create_with_resource_system(node->app_num, node->icon_resource_id); PBL_ASSERTN(watchfaces_glance->icon); // Update the active watchface title in the glance's subtitle prv_update_active_watchface_title(watchfaces_glance); const bool should_consider_slices = false; LauncherAppGlanceStructured *structured_glance = launcher_app_glance_structured_create(&node->uuid, &s_watchfaces_structured_glance_impl, should_consider_slices, watchfaces_glance); PBL_ASSERTN(structured_glance); return &structured_glance->glance; }
(watchfaces_glance->title, node->name, title_size)
<|repo_name|>pebble <|file_sep|>src/fw/apps/system_apps/launcher/default/launcher_app_glance_watchfaces.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "launcher_app_glance_watchfaces.h" #include "launcher_app_glance_structured.h" #include "kernel/events.h" #include "kernel/pbl_malloc.h" #include "process_management/app_install_manager.h" #include "shell/normal/watchface.h" #include "system/passert.h" #include "util/attributes.h" #include "util/string.h" #include "util/struct.h" #include <stdio.h> typedef struct LauncherAppGlanceWatchfaces { char title[APP_NAME_SIZE_BYTES]; char subtitle[APP_NAME_SIZE_BYTES]; KinoReel *icon; } LauncherAppGlanceWatchfaces; static KinoReel *prv_get_icon(LauncherAppGlanceStructured *structured_glance) { LauncherAppGlanceWatchfaces *watchfaces_glance = launcher_app_glance_structured_get_data(structured_glance); return NULL_SAFE_FIELD_ACCESS(watchfaces_glance, icon, NULL); } static const char *prv_get_title(LauncherAppGlanceStructured *structured_glance) { LauncherAppGlanceWatchfaces *watchfaces_glance = launcher_app_glance_structured_get_data(structured_glance); return NULL_SAFE_FIELD_ACCESS(watchfaces_glance, title, NULL); } static void prv_watchfaces_glance_subtitle_dynamic_text_node_update( UNUSED GContext *ctx, UNUSED GTextNode *node, UNUSED const GRect *box, UNUSED const GTextNodeDrawConfig *config, UNUSED bool render, char *buffer, size_t buffer_size, void *user_data) { LauncherAppGlanceStructured *structured_glance = user_data; LauncherAppGlanceWatchfaces *watchfaces_glance = launcher_app_glance_structured_get_data(structured_glance); if (watchfaces_glance) { strncpy(buffer, watchfaces_glance->subtitle, buffer_size); buffer[buffer_size - 1] = '\0'; } } static GTextNode *prv_create_subtitle_node(LauncherAppGlanceStructured *structured_glance) { return launcher_app_glance_structured_create_subtitle_text_node( structured_glance, prv_watchfaces_glance_subtitle_dynamic_text_node_update); } static void prv_destructor(LauncherAppGlanceStructured *structured_glance) { LauncherAppGlanceWatchfaces *watchfaces_glance = launcher_app_glance_structured_get_data(structured_glance); if (watchfaces_glance) { kino_reel_destroy(watchfaces_glance->icon); } app_free(watchfaces_glance); } static void prv_update_active_watchface_title(LauncherAppGlanceWatchfaces *watchfaces_glance) { const AppInstallId selected_watch_id = watchface_get_default_install_id(); AppInstallEntry entry; if (app_install_get_entry_for_install_id(selected_watch_id, &entry)) { const size_t watchfaces_subtitle_size = sizeof(watchfaces_glance->subtitle); strncpy(watchfaces_glance->subtitle, entry.name, watchfaces_subtitle_size); watchfaces_glance->subtitle[watchfaces_subtitle_size - 1] = '\0'; } } static const LauncherAppGlanceStructuredImpl s_watchfaces_structured_glance_impl = { .get_icon = prv_get_icon, .get_title = prv_get_title, .create_subtitle_node = prv_create_subtitle_node, .destructor = prv_destructor, }; LauncherAppGlance *launcher_app_glance_watchfaces_create(const AppMenuNode *node) { PBL_ASSERTN(node); LauncherAppGlanceWatchfaces *watchfaces_glance = app_zalloc_check(sizeof(*watchfaces_glance)); // Copy the name of the Watchfaces app as the title const size_t title_size = sizeof(watchfaces_glance->title); strncpy<|fim_suffix|>; watchfaces_glance->title[title_size - 1] = '\0'; // Create the icon for the Watchfaces app watchfaces_glance->icon = kino_reel_create_with_resource_system(node->app_num, node->icon_resource_id); PBL_ASSERTN(watchfaces_glance->icon); // Update the active watchface title in the glance's subtitle prv_update_active_watchface_title(watchfaces_glance); const bool should_consider_slices = false; LauncherAppGlanceStructured *structured_glance = launcher_app_glance_structured_create(&node->uuid, &s_watchfaces_structured_glance_impl, should_consider_slices, watchfaces_glance); PBL_ASSERTN(structured_glance); return &structured_glance->glance; } <|fim_middle|>(watchfaces_glance->title, node->name, title_size)<|endoftext|>
masked_node
call_expression
tests/fw/graphics/test_graphics_context.template.c
s_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); setup_test(&context, false, 2, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); setup_test(&context, false, SW_EVEN, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); setup_test(&context, false, SW_ODD, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); ASSERT_NO_CHANGE(graphics_fill_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_fill_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_fill_round_rect(&context, &GRect(20, 80, 40, 10), 4, GCornersAll)); setup_test(&context, true, 1, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); setup_test(&context, true, 2, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); setup_test(&context, true, SW_EVEN, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); setup_test(&context, true, SW_ODD, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); ASSERT_NO_CHANGE(graphics_fill_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_fill_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_fill_round_rect(&context, &GRect(20, 80, 40, 10), 4, GCornersAll)); } void test_graphics_context_${BIT_DEPTH_NAME}__lock_context(void) { GDrawState draw_state; context.lock = true; // Stroke Color draw_state = graphics_context_get_drawing_state(&context); graphics_context_set_stroke_color(&context, GColorBlue); cl_assert(memcmp(&draw_state, &context.draw_state, sizeof(GDrawState)) == 0); // Fill Color draw_state = graphics_context_get_drawing_state(&context); graphics_context_set_fill_color(&context, GColorGreen); cl_assert(memcmp(&draw_state, &context.draw_state, sizeof(GDrawState)) == 0); // Compositing Mode draw_state = graphics_context_get_drawing_state(&context); graphics_context_set_compositing_mode(&context, GCompOpOr); cl_assert(memcmp(&draw_state, &context.draw_state, sizeof(GDrawState)) == 0); // Text Color draw_state =
; graphics_context_set_text_color(&context, GColorRed); cl_assert(memcmp(&draw_state, &context.draw_state, sizeof(GDrawState)) == 0); // Antialiased draw_state = graphics_context_get_drawing_state(&context); graphics_context_set_antialiased(&context, true); cl_assert(memcmp(&draw_state, &context.draw_state, sizeof(GDrawState)) == 0); // Stroke Width draw_state = graphics_context_get_drawing_state(&context); graphics_context_set_stroke_width(&context, 11); cl_assert(memcmp(&draw_state, &context.draw_state, sizeof(GDrawState)) == 0); } void test_graphics_context_${BIT_DEPTH_NAME}__lock_framebuffer(void) { FrameBuffer fb = {}; framebuffer_init(&fb, &(GSize) {DISP_COLS, DISP_ROWS}); GContext ctx = {.dest_bitmap.info = { .format = GBITMAP_NATIVE_FORMAT, .version = GBITMAP_VERSION_CURRENT, }, .parent_framebuffer=&fb}; GBitmap *framebuffer = graphics_capture_frame_buffer(&ctx); cl_assert(ctx.lock == true); cl_assert_equal_p(framebuffer, &ctx.dest_bitmap); // Test releasing on any platform cl_assert(fb.is_dirty == false); graphics_release_frame_buffer(&ctx, framebuffer); cl_assert(ctx.lock == false); cl_assert(fb.is_dirty == true); }; void test_graphics_context_${BIT_DEPTH_NAME}__lock_framebuffer_8BitCircular(void) { // Test for locking of requested framebuffer format GContext ctx = {.dest_bitmap.info.format = GBitmapFormat8BitCircular}; GBitmap *bmp = graphics_capture_frame_buffer_format(&ctx, GBitmapFormat8BitCircular); cl_assert_equal_p(bmp, &ctx.dest_bitmap); cl_assert(ctx.lock == true); }; void test_graphics_context_${BIT_DEPTH_NAME}__lock_framebuffer_fails_from_8BitCircular(void) { // Test for locking of 8Bit Circular framebuffer when framebuffer is regular 8Bit GContext ctx = {.dest_bitmap.info.format = GBitmapFormat8BitCircular}; GBitmap *bmp = graphics_capture_frame_buffer_format(&ctx, GBitmapFormat8Bit); cl_assert(ctx.lock == false); cl_assert_equal_p(bmp, NULL); }; void test_graphics_context_${BIT_DEPTH_NAME}__lock_framebuffer_1Bit_on_8BitCircular_must_fail(void) { // Test for locking of 1Bit framebuffer when frambuffer is 8Bit Circular GContext ctx = {.dest_bitmap.info.format = GBitmapFormat8BitCircular}; GBitmap *bmp = graphics_capture_frame_buffer_format(&ctx, GBitmapFormat1Bit); cl_assert(ctx.lock == false); cl_assert_equal_p(bmp, NULL); }; void test_graphics_context_${BIT_DEPTH_NAME}__lock_framebuffer_2BitPalette_must_fail(void) { // Ensure that the code path for unsupported capture formats leaves the GContext unlocked. GContext ctx = {.dest_bitmap.info.format = GBitmapFormat8Bit}; GBitmap *bmp = graphics_capture_frame_buffer_format(&ctx, GBitmapFormat2BitPalette); cl_assert(ctx.lock == false); cl_assert_equal_p(bmp, NULL); }
graphics_context_get_drawing_state(&context)
<|repo_name|>pebble <|file_sep|>tests/fw/graphics/test_graphics_context.template.c <|fim_prefix|>s_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); setup_test(&context, false, 2, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); setup_test(&context, false, SW_EVEN, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); setup_test(&context, false, SW_ODD, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); ASSERT_NO_CHANGE(graphics_fill_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_fill_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_fill_round_rect(&context, &GRect(20, 80, 40, 10), 4, GCornersAll)); setup_test(&context, true, 1, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); setup_test(&context, true, 2, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); setup_test(&context, true, SW_EVEN, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); setup_test(&context, true, SW_ODD, GColorBlack, GColorBlack, true); ASSERT_NO_CHANGE(graphics_draw_line(&context, GPoint(5, 5), GPoint(45, 10))); ASSERT_NO_CHANGE(graphics_draw_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_draw_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_draw_round_rect(&context, &GRect(20, 80, 40, 10), 4)); ASSERT_NO_CHANGE(graphics_fill_rect(&context, &GRect(10, 20, 40, 10))); ASSERT_NO_CHANGE(graphics_fill_circle(&context, GPoint(50, 50), 10)); ASSERT_NO_CHANGE(graphics_fill_round_rect(&context, &GRect(20, 80, 40, 10), 4, GCornersAll)); } void test_graphics_context_${BIT_DEPTH_NAME}__lock_context(void) { GDrawState draw_state; context.lock = true; // Stroke Color draw_state = graphics_context_get_drawing_state(&context); graphics_context_set_stroke_color(&context, GColorBlue); cl_assert(memcmp(&draw_state, &context.draw_state, sizeof(GDrawState)) == 0); // Fill Color draw_state = graphics_context_get_drawing_state(&context); graphics_context_set_fill_color(&context, GColorGreen); cl_assert(memcmp(&draw_state, &context.draw_state, sizeof(GDrawState)) == 0); // Compositing Mode draw_state = graphics_context_get_drawing_state(&context); graphics_context_set_compositing_mode(&context, GCompOpOr); cl_assert(memcmp(&draw_state, &context.draw_state, sizeof(GDrawState)) == 0); // Text Color draw_state = <|fim_suffix|>; graphics_context_set_text_color(&context, GColorRed); cl_assert(memcmp(&draw_state, &context.draw_state, sizeof(GDrawState)) == 0); // Antialiased draw_state = graphics_context_get_drawing_state(&context); graphics_context_set_antialiased(&context, true); cl_assert(memcmp(&draw_state, &context.draw_state, sizeof(GDrawState)) == 0); // Stroke Width draw_state = graphics_context_get_drawing_state(&context); graphics_context_set_stroke_width(&context, 11); cl_assert(memcmp(&draw_state, &context.draw_state, sizeof(GDrawState)) == 0); } void test_graphics_context_${BIT_DEPTH_NAME}__lock_framebuffer(void) { FrameBuffer fb = {}; framebuffer_init(&fb, &(GSize) {DISP_COLS, DISP_ROWS}); GContext ctx = {.dest_bitmap.info = { .format = GBITMAP_NATIVE_FORMAT, .version = GBITMAP_VERSION_CURRENT, }, .parent_framebuffer=&fb}; GBitmap *framebuffer = graphics_capture_frame_buffer(&ctx); cl_assert(ctx.lock == true); cl_assert_equal_p(framebuffer, &ctx.dest_bitmap); // Test releasing on any platform cl_assert(fb.is_dirty == false); graphics_release_frame_buffer(&ctx, framebuffer); cl_assert(ctx.lock == false); cl_assert(fb.is_dirty == true); }; void test_graphics_context_${BIT_DEPTH_NAME}__lock_framebuffer_8BitCircular(void) { // Test for locking of requested framebuffer format GContext ctx = {.dest_bitmap.info.format = GBitmapFormat8BitCircular}; GBitmap *bmp = graphics_capture_frame_buffer_format(&ctx, GBitmapFormat8BitCircular); cl_assert_equal_p(bmp, &ctx.dest_bitmap); cl_assert(ctx.lock == true); }; void test_graphics_context_${BIT_DEPTH_NAME}__lock_framebuffer_fails_from_8BitCircular(void) { // Test for locking of 8Bit Circular framebuffer when framebuffer is regular 8Bit GContext ctx = {.dest_bitmap.info.format = GBitmapFormat8BitCircular}; GBitmap *bmp = graphics_capture_frame_buffer_format(&ctx, GBitmapFormat8Bit); cl_assert(ctx.lock == false); cl_assert_equal_p(bmp, NULL); }; void test_graphics_context_${BIT_DEPTH_NAME}__lock_framebuffer_1Bit_on_8BitCircular_must_fail(void) { // Test for locking of 1Bit framebuffer when frambuffer is 8Bit Circular GContext ctx = {.dest_bitmap.info.format = GBitmapFormat8BitCircular}; GBitmap *bmp = graphics_capture_frame_buffer_format(&ctx, GBitmapFormat1Bit); cl_assert(ctx.lock == false); cl_assert_equal_p(bmp, NULL); }; void test_graphics_context_${BIT_DEPTH_NAME}__lock_framebuffer_2BitPalette_must_fail(void) { // Ensure that the code path for unsupported capture formats leaves the GContext unlocked. GContext ctx = {.dest_bitmap.info.format = GBitmapFormat8Bit}; GBitmap *bmp = graphics_capture_frame_buffer_format(&ctx, GBitmapFormat2BitPalette); cl_assert(ctx.lock == false); cl_assert_equal_p(bmp, NULL); } <|fim_middle|>graphics_context_get_drawing_state(&context)<|endoftext|>
masked_node
call_expression
src/fw/services/normal/timeline/sports_layout.c
eConstructorConfig s_subtitle_config = { .extent.node.type = LayoutNodeType_Constructor, .constructor = prv_subtitle_constructor, }; static const LayoutNodeConstructorConfig s_game_config = { .extent.node.type = LayoutNodeType_Constructor, .constructor = prv_game_constructor, }; static const LayoutNodeExtentConfig s_icon_config = { .node.type = LayoutNodeType_TimelineIcon, .offset.y = PBL_IF_RECT_ELSE(5, 11), // icon offset y .margin.h = PBL_IF_RECT_ELSE(5, 11), // icon margin height }; static const LayoutNodeConfig s_page_break_config = { .type = LayoutNodeType_TimelinePageBreak, }; static const LayoutNodeTextAttributeConfig s_body_config = { .attr_id = AttributeIdBody, .text.font_key = FONT_KEY_GOTHIC_24_BOLD, .text.line_spacing_delta = CARD_LINE_DELTA, .text.extent.margin.h = 14, // body margin height }; static const LayoutNodeConstructorConfig s_broadcaster_header_config = { .extent.node.type = LayoutNodeType_Constructor, .constructor = prv_broadcaster_header_constructor, }; static const LayoutNodeTextAttributeConfig s_broadcaster_config = { .attr_id = AttributeIdBroadcaster, .text.font_key = FONT_KEY_GOTHIC_24_BOLD, .text.line_spacing_delta = CARD_LINE_DELTA, .text.extent.margin.h = 8, // broadcaster margin height }; static const LayoutNodeConfig * const s_vertical_config_nodes[] = { &s_subtitle_config.extent.node, &s_game_config.extent.node, &s_icon_config.node, &s_page_break_config, &s_body_config.text.extent.node, &s_broadcaster_header_config.extent.node, &s_broadcaster_config.text.extent.node, }; static const LayoutNodeVerticalConfig s_vertical_config = { .container.extent.node.type = LayoutNodeType_Vertical, .container.num_nodes = ARRAY_LENGTH(s_vertical_config_nodes), .container.nodes = (LayoutNodeConfig **)&s_vertical_config_nodes, .container.extent.offset.y = CARD_MARGIN_TOP, .container.extent.margin.h = CARD_MARGIN_TOP + CARD_MARGIN_BOTTOM, }; return timeline_layout_create_card_view_from_config(timeline_layout, &s_vertical_config.container.extent.node); } static GTextNode *prv_create_team_node(const LayoutLayer *layout_ref, int team_offset) { const SportsLayout *layout = (const SportsLayout *)layout_ref; AttributeList *attributes = layout->timeline_layout.layout_layer.attributes; const bool is_pregame = (layout->state == GameStatePreGame); const bool has_record = (attribute_find(attributes, AttributeIdRecordAway + team_offset) != NULL); const AttributeId large_attr = !is_pregame ? AttributeIdScoreAway : AttributeIdNameAway; const AttributeId small_attr = !is_pregame ? AttributeIdNameAway : has_record ? AttributeIdRecordAway : AttributeIdRankAway; const char *large_font = is_pregame ? FONT_KEY_GOTHIC_28_BOLD : FONT_KEY_LECO_26_BOLD_NUMBERS_AM_PM; const char *small_font = FONT_KEY_GOTHIC_18_BOLD; const LayoutNodeTextAttributeConfig large_config = { .attr_id = large_attr + team_offset, .text.font_key = large_font, #if PBL_COLOR .text.color = LayoutColor_Secondary, #endif .text.fixed_lines = 1, // large fixed lines .text.alignment = LayoutTextAlignment_Center, .text.extent.margin.h = -2, // large margin height }; const LayoutNodeTextAttributeConfig small_config = { .attr_id = small_attr + team_offset, .text.font_key = small_font, #if PBL_COLOR .text.color = LayoutColor_Secondary, #endif .text.fixed_lines = 1, // small fixed lines .text.alignment = LayoutTextAlignment_Center, }; const LayoutNodeConfig * const vertical_config_nodes[] = { &large_config.text.extent.node, &small_config.text.extent.node, }; const LayoutNodeVerticalConfig vertical_config = { .container.extent.node.type = LayoutNodeType_Vertical, .container.num_nodes =
, .container.nodes = (LayoutNodeConfig **)&vertical_config_nodes, .container.extent.offset.y = CARD_MARGIN_TOP, .container.extent.margin.h = CARD_MARGIN_TOP + CARD_MARGIN_BOTTOM, }; GTextNodeVertical *vertical_node = (GTextNodeVertical *)layout_create_text_node_from_config( layout_ref, &vertical_config.container.extent.node); const GRect *bounds = &((Layer *)layout)->bounds; const int16_t midwidth = bounds->size.w / 2 - TIMELINE_CARD_MARGIN; vertical_node->container.size.w = midwidth; return &vertical_node->container.node; } ////////////////////////////////////////// // LayoutLayer API ////////////////////////////////////////// bool sports_layout_verify(bool existing_attributes[]) { return existing_attributes[AttributeIdTitle]; } LayoutLayer *sports_layout_create(const LayoutLayerConfig *config) { SportsLayout *layout = task_zalloc_check(sizeof(SportsLayout)); static const TimelineLayoutImpl s_timeline_layout_impl = { .attributes = { AttributeIdTitle, AttributeIdSubtitle }, .default_colors = { { .argb = GColorBlackARGB8 }, { .argb = GColorWhiteARGB8 }, { .argb = GColorVividCeruleanARGB8 } }, .default_icon = TIMELINE_RESOURCE_TIMELINE_SPORTS, .card_icon_align = GAlignCenter, .card_icon_size = TimelineResourceSizeSmall, .card_view_constructor = prv_card_view_constructor, }; timeline_layout_init((TimelineLayout *)layout, config, &s_timeline_layout_impl); return (LayoutLayer *)layout; } #else LayoutLayer *sports_layout_create(const LayoutLayerConfig *config) { return NULL; } bool sports_layout_verify(bool existing_attributes[]) { return false; } #endif
ARRAY_LENGTH(vertical_config_nodes)
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/timeline/sports_layout.c <|fim_prefix|>eConstructorConfig s_subtitle_config = { .extent.node.type = LayoutNodeType_Constructor, .constructor = prv_subtitle_constructor, }; static const LayoutNodeConstructorConfig s_game_config = { .extent.node.type = LayoutNodeType_Constructor, .constructor = prv_game_constructor, }; static const LayoutNodeExtentConfig s_icon_config = { .node.type = LayoutNodeType_TimelineIcon, .offset.y = PBL_IF_RECT_ELSE(5, 11), // icon offset y .margin.h = PBL_IF_RECT_ELSE(5, 11), // icon margin height }; static const LayoutNodeConfig s_page_break_config = { .type = LayoutNodeType_TimelinePageBreak, }; static const LayoutNodeTextAttributeConfig s_body_config = { .attr_id = AttributeIdBody, .text.font_key = FONT_KEY_GOTHIC_24_BOLD, .text.line_spacing_delta = CARD_LINE_DELTA, .text.extent.margin.h = 14, // body margin height }; static const LayoutNodeConstructorConfig s_broadcaster_header_config = { .extent.node.type = LayoutNodeType_Constructor, .constructor = prv_broadcaster_header_constructor, }; static const LayoutNodeTextAttributeConfig s_broadcaster_config = { .attr_id = AttributeIdBroadcaster, .text.font_key = FONT_KEY_GOTHIC_24_BOLD, .text.line_spacing_delta = CARD_LINE_DELTA, .text.extent.margin.h = 8, // broadcaster margin height }; static const LayoutNodeConfig * const s_vertical_config_nodes[] = { &s_subtitle_config.extent.node, &s_game_config.extent.node, &s_icon_config.node, &s_page_break_config, &s_body_config.text.extent.node, &s_broadcaster_header_config.extent.node, &s_broadcaster_config.text.extent.node, }; static const LayoutNodeVerticalConfig s_vertical_config = { .container.extent.node.type = LayoutNodeType_Vertical, .container.num_nodes = ARRAY_LENGTH(s_vertical_config_nodes), .container.nodes = (LayoutNodeConfig **)&s_vertical_config_nodes, .container.extent.offset.y = CARD_MARGIN_TOP, .container.extent.margin.h = CARD_MARGIN_TOP + CARD_MARGIN_BOTTOM, }; return timeline_layout_create_card_view_from_config(timeline_layout, &s_vertical_config.container.extent.node); } static GTextNode *prv_create_team_node(const LayoutLayer *layout_ref, int team_offset) { const SportsLayout *layout = (const SportsLayout *)layout_ref; AttributeList *attributes = layout->timeline_layout.layout_layer.attributes; const bool is_pregame = (layout->state == GameStatePreGame); const bool has_record = (attribute_find(attributes, AttributeIdRecordAway + team_offset) != NULL); const AttributeId large_attr = !is_pregame ? AttributeIdScoreAway : AttributeIdNameAway; const AttributeId small_attr = !is_pregame ? AttributeIdNameAway : has_record ? AttributeIdRecordAway : AttributeIdRankAway; const char *large_font = is_pregame ? FONT_KEY_GOTHIC_28_BOLD : FONT_KEY_LECO_26_BOLD_NUMBERS_AM_PM; const char *small_font = FONT_KEY_GOTHIC_18_BOLD; const LayoutNodeTextAttributeConfig large_config = { .attr_id = large_attr + team_offset, .text.font_key = large_font, #if PBL_COLOR .text.color = LayoutColor_Secondary, #endif .text.fixed_lines = 1, // large fixed lines .text.alignment = LayoutTextAlignment_Center, .text.extent.margin.h = -2, // large margin height }; const LayoutNodeTextAttributeConfig small_config = { .attr_id = small_attr + team_offset, .text.font_key = small_font, #if PBL_COLOR .text.color = LayoutColor_Secondary, #endif .text.fixed_lines = 1, // small fixed lines .text.alignment = LayoutTextAlignment_Center, }; const LayoutNodeConfig * const vertical_config_nodes[] = { &large_config.text.extent.node, &small_config.text.extent.node, }; const LayoutNodeVerticalConfig vertical_config = { .container.extent.node.type = LayoutNodeType_Vertical, .container.num_nodes = <|fim_suffix|>, .container.nodes = (LayoutNodeConfig **)&vertical_config_nodes, .container.extent.offset.y = CARD_MARGIN_TOP, .container.extent.margin.h = CARD_MARGIN_TOP + CARD_MARGIN_BOTTOM, }; GTextNodeVertical *vertical_node = (GTextNodeVertical *)layout_create_text_node_from_config( layout_ref, &vertical_config.container.extent.node); const GRect *bounds = &((Layer *)layout)->bounds; const int16_t midwidth = bounds->size.w / 2 - TIMELINE_CARD_MARGIN; vertical_node->container.size.w = midwidth; return &vertical_node->container.node; } ////////////////////////////////////////// // LayoutLayer API ////////////////////////////////////////// bool sports_layout_verify(bool existing_attributes[]) { return existing_attributes[AttributeIdTitle]; } LayoutLayer *sports_layout_create(const LayoutLayerConfig *config) { SportsLayout *layout = task_zalloc_check(sizeof(SportsLayout)); static const TimelineLayoutImpl s_timeline_layout_impl = { .attributes = { AttributeIdTitle, AttributeIdSubtitle }, .default_colors = { { .argb = GColorBlackARGB8 }, { .argb = GColorWhiteARGB8 }, { .argb = GColorVividCeruleanARGB8 } }, .default_icon = TIMELINE_RESOURCE_TIMELINE_SPORTS, .card_icon_align = GAlignCenter, .card_icon_size = TimelineResourceSizeSmall, .card_view_constructor = prv_card_view_constructor, }; timeline_layout_init((TimelineLayout *)layout, config, &s_timeline_layout_impl); return (LayoutLayer *)layout; } #else LayoutLayer *sports_layout_create(const LayoutLayerConfig *config) { return NULL; } bool sports_layout_verify(bool existing_attributes[]) { return false; } #endif <|fim_middle|>ARRAY_LENGTH(vertical_config_nodes)<|endoftext|>
prefix_only
argument_list
src/fw/apps/demo_apps/flash_test.c
fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); layer_add_child(&window->layer, &msg_text_layer->layer); msg_text_layer = &data->msg_text_layer[2]; text_layer_init(msg_text_layer, &GRect(0, 64, window->layer.bounds.size.w, 40)); if (data->test_case >= FLASH_TEST_CASE_RUN_SWITCH_MODE_ASYNC) { text_layer_set_text(msg_text_layer, "Press Back To Exit"); } else { text_layer_set_text(msg_text_layer, "Press Up to Exit, Down to Stop Test"); } text_layer_set_text_alignment(msg_text_layer, GTextAlignmentCenter); text_layer_set_background_color(msg_text_layer, GColorBlack); text_layer_set_text_color(msg_text_layer, GColorWhite); text_layer_set_font(msg_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); layer_add_child(&window->layer, &msg_text_layer->layer); TextLayer *status_text_layer = &data->status_text_layer; text_layer_init(status_text_layer, &GRect(0, 106, window->layer.bounds.size.w, 40)); text_layer_set_text_alignment(status_text_layer, GTextAlignmentCenter); text_layer_set_background_color(status_text_layer, GColorBlack); text_layer_set_text_color(status_text_layer, GColorWhite); text_layer_set_font(status_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); layer_add_child(&window->layer, &status_text_layer->layer); update_test_case_status(data); } void flash_test_dismiss_window(void) { struct FlashTestData *data = app_state_get_user_data(); const bool animated = true; window_stack_remove(&data->test_window, animated); } static void up_click_handler(ClickRecognizerRef recognizer, void *unusued) { struct FlashTestData *data = app_state_get_user_data(); if (data->test_case_status != FLASH_TEST_STATUS_RUNNING) { flash_test_dismiss_window(); } } static void down_click_handler(ClickRecognizerRef recognizer, void *unusued) { struct FlashTestData *data = app_state_get_user_data(); // Only stop stress test if ((data->test_case == FLASH_TEST_CASE_RUN_STRESS_ADDR_TEST) && (data->test_case_status == FLASH_TEST_STATUS_RUNNING)) { data->test_case_status = FLASH_TEST_STATUS_STOPPED; stop_flash_test_case(); update_test_case_status(data); } } static void run_test(void* context) { struct FlashTestData *data = app_state_get_user_data(); FlashTestErrorType status = FLASH_TEST_SUCCESS; // Execute test - pass in 0 by default for iterations status = run_flash_test_case(data->test_case, 0); if (status == FLASH_TEST_SUCCESS) { data->test_case_status = FLASH_TEST_STATUS_PASSED; } else { PBL_LOG(LOG_LEVEL_DEBUG, ">>>>>FAILED TEST CASE<<<<<"); data->test_case_status = FLASH_TEST_STATUS_FAILED; } update_test_case_status(data); } static void select_click_handler(ClickRecognizerRef recognizer, void *unusued) { struct FlashTestData *data = app_state_get_user_data(); if ((data->test_case == FLASH_TEST_CASE_RUN_STRESS_ADDR_TEST) && (data->test_case_status == FLASH_TEST_STATUS_RUNNING)) { data->test_case_status = FLASH_TEST_STATUS_STOPPED; stop_flash_test_case(); update_test_case_status(data); } else if (data->test_case_status == FLASH_TEST_STATUS_INIT) { data->test_case_status = FLASH_TEST_STATUS_RUNNING; update_test_case_status(data); system_task_add_callback(run_test, NULL); } } static void click_config_provider(void *context) { window_single_click_subscribe(BUTTON_ID_UP, (ClickHandler)up_click_handler); window_single_click_subscribe(BUTTON_ID_DOWN, (ClickHandler)down_click_handler); window_single_click_subscribe(BUTTON_ID_SELECT, (ClickHandler)select_click_handler); } static void flash_test_select_callback(int index, void *context) { struct FlashTestData *data = (struct FlashTestData *) context; data->test_case = index; data->test_case_status = FLASH_TEST_STATUS_INIT; // Display window for running test case // Init the window Window *test_window = &data->test_window; window_init(test_window, WINDOW_NAME("Test Case")); window_set_window_handlers(test_window, &(WindowHandlers) { .load = test_window_load, }); window_set_user_data
(test_window, data)
<|repo_name|>pebble <|file_sep|>src/fw/apps/demo_apps/flash_test.c <|fim_prefix|> fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); layer_add_child(&window->layer, &msg_text_layer->layer); msg_text_layer = &data->msg_text_layer[2]; text_layer_init(msg_text_layer, &GRect(0, 64, window->layer.bounds.size.w, 40)); if (data->test_case >= FLASH_TEST_CASE_RUN_SWITCH_MODE_ASYNC) { text_layer_set_text(msg_text_layer, "Press Back To Exit"); } else { text_layer_set_text(msg_text_layer, "Press Up to Exit, Down to Stop Test"); } text_layer_set_text_alignment(msg_text_layer, GTextAlignmentCenter); text_layer_set_background_color(msg_text_layer, GColorBlack); text_layer_set_text_color(msg_text_layer, GColorWhite); text_layer_set_font(msg_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); layer_add_child(&window->layer, &msg_text_layer->layer); TextLayer *status_text_layer = &data->status_text_layer; text_layer_init(status_text_layer, &GRect(0, 106, window->layer.bounds.size.w, 40)); text_layer_set_text_alignment(status_text_layer, GTextAlignmentCenter); text_layer_set_background_color(status_text_layer, GColorBlack); text_layer_set_text_color(status_text_layer, GColorWhite); text_layer_set_font(status_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); layer_add_child(&window->layer, &status_text_layer->layer); update_test_case_status(data); } void flash_test_dismiss_window(void) { struct FlashTestData *data = app_state_get_user_data(); const bool animated = true; window_stack_remove(&data->test_window, animated); } static void up_click_handler(ClickRecognizerRef recognizer, void *unusued) { struct FlashTestData *data = app_state_get_user_data(); if (data->test_case_status != FLASH_TEST_STATUS_RUNNING) { flash_test_dismiss_window(); } } static void down_click_handler(ClickRecognizerRef recognizer, void *unusued) { struct FlashTestData *data = app_state_get_user_data(); // Only stop stress test if ((data->test_case == FLASH_TEST_CASE_RUN_STRESS_ADDR_TEST) && (data->test_case_status == FLASH_TEST_STATUS_RUNNING)) { data->test_case_status = FLASH_TEST_STATUS_STOPPED; stop_flash_test_case(); update_test_case_status(data); } } static void run_test(void* context) { struct FlashTestData *data = app_state_get_user_data(); FlashTestErrorType status = FLASH_TEST_SUCCESS; // Execute test - pass in 0 by default for iterations status = run_flash_test_case(data->test_case, 0); if (status == FLASH_TEST_SUCCESS) { data->test_case_status = FLASH_TEST_STATUS_PASSED; } else { PBL_LOG(LOG_LEVEL_DEBUG, ">>>>>FAILED TEST CASE<<<<<"); data->test_case_status = FLASH_TEST_STATUS_FAILED; } update_test_case_status(data); } static void select_click_handler(ClickRecognizerRef recognizer, void *unusued) { struct FlashTestData *data = app_state_get_user_data(); if ((data->test_case == FLASH_TEST_CASE_RUN_STRESS_ADDR_TEST) && (data->test_case_status == FLASH_TEST_STATUS_RUNNING)) { data->test_case_status = FLASH_TEST_STATUS_STOPPED; stop_flash_test_case(); update_test_case_status(data); } else if (data->test_case_status == FLASH_TEST_STATUS_INIT) { data->test_case_status = FLASH_TEST_STATUS_RUNNING; update_test_case_status(data); system_task_add_callback(run_test, NULL); } } static void click_config_provider(void *context) { window_single_click_subscribe(BUTTON_ID_UP, (ClickHandler)up_click_handler); window_single_click_subscribe(BUTTON_ID_DOWN, (ClickHandler)down_click_handler); window_single_click_subscribe(BUTTON_ID_SELECT, (ClickHandler)select_click_handler); } static void flash_test_select_callback(int index, void *context) { struct FlashTestData *data = (struct FlashTestData *) context; data->test_case = index; data->test_case_status = FLASH_TEST_STATUS_INIT; // Display window for running test case // Init the window Window *test_window = &data->test_window; window_init(test_window, WINDOW_NAME("Test Case")); window_set_window_handlers(test_window, &(WindowHandlers) { .load = test_window_load, }); window_set_user_data<|fim_suffix|><|fim_middle|>(test_window, data)<|endoftext|>
prefix_only
call_expression
tests/fakes/fake_put_bytes_storage_mem.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "fake_put_bytes_storage_mem.h" #include "clar_asserts.h" #include "kernel/pbl_malloc.h" #include "services/common/put_bytes/put_bytes_storage_internal.h" #include "system/passert.h" #define FAKE_STORAGE_MAX_SIZE (512 * 1024) typedef struct FakePutBytesStorageData { PutBytesStorageInfo *info; bool last_is_success; uint32_t crc; uint32_t total_size; uint8_t buffer[FAKE_STORAGE_MAX_SIZE]; } FakePutBytesStorageData; FakePutBytesStorageData s_storage_data; bool pb_storage_raw_get_status(PutBytesObjectType obj_type, PbInstallStatus *status) { return false; } static bool fake_pb_storage_mem_init(PutBytesStorage *storage, PutBytesObjectType object_type, uint32_t total_size, PutBytesStorageInfo *info, uint32_t append_offset) { // This fake only supports one put bytes storage to be init'd at a time. PBL_ASSERTN(!s_storage_data.total_size); size_t buffer_size = total_size + sizeof(FirmwareDescription); memset(s_storage_data.buffer, 0, sizeof(s_storage_data.buffer)); s_storage_data.total_size = buffer_size; PutBytesStorageInfo *info_copy = NULL; if (info) { info_copy = (PutBytesStorageInfo *)kernel_malloc_check(sizeof(PutBytesStorageInfo)); *info_copy = *info; } s_storage_data.info = info_copy; storage->impl_data = &s_storage_data; // put_bytes_storage_raw.c is weird, it reserves space at the beginning for FirmwareDescription: storage->current_offset = sizeof(FirmwareDescription); return true; } uint32_t fake_pb_storage_mem_get_max_size(PutBytesObjectType object_type) { return FAKE_STORAGE_MAX_SIZE; } static void(*s_do_before_write)(void) = NULL; static void fake_pb_storage_mem_write(PutBytesStorage *storage, uint32_t offset, const uint8_t *buffer, uint32_t length) { PBL_ASSERTN(s_storage_data.total_size); PBL_ASSERTN(offset + length <= s_storage_data.total_size); if (s_do_before_write) { s_do_before_write(); s_do_before_write = NULL; }
memcpy(s_storage_data.buffer + offset, buffer, length)
<|repo_name|>pebble <|file_sep|>tests/fakes/fake_put_bytes_storage_mem.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "fake_put_bytes_storage_mem.h" #include "clar_asserts.h" #include "kernel/pbl_malloc.h" #include "services/common/put_bytes/put_bytes_storage_internal.h" #include "system/passert.h" #define FAKE_STORAGE_MAX_SIZE (512 * 1024) typedef struct FakePutBytesStorageData { PutBytesStorageInfo *info; bool last_is_success; uint32_t crc; uint32_t total_size; uint8_t buffer[FAKE_STORAGE_MAX_SIZE]; } FakePutBytesStorageData; FakePutBytesStorageData s_storage_data; bool pb_storage_raw_get_status(PutBytesObjectType obj_type, PbInstallStatus *status) { return false; } static bool fake_pb_storage_mem_init(PutBytesStorage *storage, PutBytesObjectType object_type, uint32_t total_size, PutBytesStorageInfo *info, uint32_t append_offset) { // This fake only supports one put bytes storage to be init'd at a time. PBL_ASSERTN(!s_storage_data.total_size); size_t buffer_size = total_size + sizeof(FirmwareDescription); memset(s_storage_data.buffer, 0, sizeof(s_storage_data.buffer)); s_storage_data.total_size = buffer_size; PutBytesStorageInfo *info_copy = NULL; if (info) { info_copy = (PutBytesStorageInfo *)kernel_malloc_check(sizeof(PutBytesStorageInfo)); *info_copy = *info; } s_storage_data.info = info_copy; storage->impl_data = &s_storage_data; // put_bytes_storage_raw.c is weird, it reserves space at the beginning for FirmwareDescription: storage->current_offset = sizeof(FirmwareDescription); return true; } uint32_t fake_pb_storage_mem_get_max_size(PutBytesObjectType object_type) { return FAKE_STORAGE_MAX_SIZE; } static void(*s_do_before_write)(void) = NULL; static void fake_pb_storage_mem_write(PutBytesStorage *storage, uint32_t offset, const uint8_t *buffer, uint32_t length) { PBL_ASSERTN(s_storage_data.total_size); PBL_ASSERTN(offset + length <= s_storage_data.total_size); if (s_do_before_write) { s_do_before_write(); s_do_before_write = NULL; } <|fim_suffix|><|fim_middle|>memcpy(s_storage_data.buffer + offset, buffer, length)<|endoftext|>
suffix_only
argument_list
tests/fw/graphics/test_graphics_draw_line.c
; } void test_graphics_draw_line__origin_layer(void) { GContext ctx; Layer layer; test_graphics_context_init(&ctx, fb); layer_init(&layer, &GRect(0, 0, 60, 60)); layer_set_update_proc(&layer, &inside_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_inside_origin_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_x_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_x_origin_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_nx_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_nx_origin_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_y_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_y_origin_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_ny_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_ny_origin_layer"))); } void test_graphics_draw_line__offset_layer(void) { GContext ctx; Layer layer; test_graphics_context_init(&ctx, fb); layer_init(&layer, &GRect(10, 10, 60, 60)); layer_set_update_proc(&layer, &inside_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_inside_offset_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_x_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_x_offset_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_nx_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_nx_offset_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_y_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_y_offset_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_ny_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_ny_offset_layer"))); } void test_graphics_draw_line__clear(void) { GContext ctx; Layer layer; test_graphics_context_init(&ctx, fb); layer_init(&layer, &GRect(0, 0, 60, 60)); layer_set_update_proc(&layer, &inside_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_inside_origin_layer"))); layer_set_update_proc(&layer, &white_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(framebuffer_is_empty("white_over_black", ctx.parent_framebuffer, GColorWhite)); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &inside_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_inside_origin_layer"))); layer_set_update_proc(&layer, &clear_layer_update_callback); layer_render_tree(&layer, &ctx); #if SCREEN_COLOR_DEPTH_BITS == 8 cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_clear"))); #else cl_check(framebuffer_is_empty("clear_over_black", ctx.parent_framebuffer, GColorWhite)); #endif } #define MAX_NUM_ROWS 168 #define MAX_NUM_COLS 144 #define ORIGIN_RECT_NO_CLIP GRect(0, 0, MAX_NUM_COLS, MAX_NUM_ROWS) #define ORIGIN_RECT_CLIP_EVEN
(ctx, GPoint(5, -30), GPoint(45, 30))
<|repo_name|>pebble <|file_sep|>tests/fw/graphics/test_graphics_draw_line.c <|fim_prefix|><|fim_suffix|>; } void test_graphics_draw_line__origin_layer(void) { GContext ctx; Layer layer; test_graphics_context_init(&ctx, fb); layer_init(&layer, &GRect(0, 0, 60, 60)); layer_set_update_proc(&layer, &inside_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_inside_origin_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_x_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_x_origin_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_nx_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_nx_origin_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_y_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_y_origin_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_ny_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_ny_origin_layer"))); } void test_graphics_draw_line__offset_layer(void) { GContext ctx; Layer layer; test_graphics_context_init(&ctx, fb); layer_init(&layer, &GRect(10, 10, 60, 60)); layer_set_update_proc(&layer, &inside_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_inside_offset_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_x_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_x_offset_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_nx_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_nx_offset_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_y_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_y_offset_layer"))); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_ny_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_across_ny_offset_layer"))); } void test_graphics_draw_line__clear(void) { GContext ctx; Layer layer; test_graphics_context_init(&ctx, fb); layer_init(&layer, &GRect(0, 0, 60, 60)); layer_set_update_proc(&layer, &inside_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_inside_origin_layer"))); layer_set_update_proc(&layer, &white_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(framebuffer_is_empty("white_over_black", ctx.parent_framebuffer, GColorWhite)); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &inside_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_inside_origin_layer"))); layer_set_update_proc(&layer, &clear_layer_update_callback); layer_render_tree(&layer, &ctx); #if SCREEN_COLOR_DEPTH_BITS == 8 cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, TEST_NAMED_PBI_FILE("draw_line_clear"))); #else cl_check(framebuffer_is_empty("clear_over_black", ctx.parent_framebuffer, GColorWhite)); #endif } #define MAX_NUM_ROWS 168 #define MAX_NUM_COLS 144 #define ORIGIN_RECT_NO_CLIP GRect(0, 0, MAX_NUM_COLS, MAX_NUM_ROWS) #define ORIGIN_RECT_CLIP_EVEN <|fim_middle|>(ctx, GPoint(5, -30), GPoint(45, 30))<|endoftext|>
masked_node
argument_list
src/fw/syscall/app_worker_syscalls.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "applib/app_worker.h" #include "kernel/event_loop.h" #include "kernel/ui/modals/modal_manager.h" #include "kernel/ui/modals/modal_manager_private.h" #include "process_management/worker_manager.h" #include "process_management/app_manager.h" #include "popups/switch_worker_ui.h" #include "syscall/syscall_internal.h" // --------------------------------------------------------------------------------------------------------------- // Determine if the worker for the current app is running DEFINE_SYSCALL(bool, sys_app_worker_is_running, void) { const PebbleProcessMd *md = worker_manager_get_current_worker_md(); if (md == NULL) { return false; } return (uuid_equal(&md->uuid, &app_manager_get_current_app_md()->uuid)); } // --------------------------------------------------------------------------------------------------------------- // Display the confirmation dialog for switching into the worker static void prv_switch_worker(void *data) { AppInstallId install_id = (AppInstallId)data; WindowStack *window_stack = modal_manager_get_window_stack(ModalPriorityGeneric); switch_worker_confirm(install_id, false /* do not set as default */, window_stack); } // Launch the worker for the current app DEFINE_SYSCALL(AppWorkerResult, sys_app_worker_launch, void) { AppInstallId install_id = app_manager_get_task_context()->install_id; // Make sure there is a worker for this app if (!app_manager_get_task_context()->app_md->has_worker) { return APP_WORKER_RESULT_NO_WORKER; } // Is there a worker already running? const PebbleProcessMd *md = worker_manager_get_current_worker_md(); if (md != NULL) { const PebbleProcessMd *app_process = app_manager_get_current_app_md(); if (uuid_equal(&md->uuid, &app_process->uuid)) { return APP_WORKER_RESULT_ALREADY_RUNNING; } // We have to get confirmation first that it is OK to launch the new worker launcher_task_add_callback(prv_switch_worker, (void *) install_id); return APP_WORKER_RESULT_ASKING_CONFIRMATION; } worker_manager_put_launch_worker_event(install_id); worker_manager_set_default_install_id(install_id); return APP_WORKER_RESULT_SUCCESS; } // --------------------------------------------------------------------------------------------------------------- // Kill the worker for the current app DEFINE_SYSCALL(AppWorkerResult, sys_app_worker_kill, void) { const PebbleProcessMd *md = worker_manager_get_current_worker_md(); if (md == NULL) { return APP_WORKER_RESULT_NOT_RUNNING; } if (!uuid_equal(&md->uuid, &app_manager_get_current_app_md()->uuid)) { return APP_WORKER_RESULT_DIFFERENT_APP; } process_manager_put_kill_process_event(PebbleTask_Worker, true /*graceful*/); return APP_WORKER_RESULT_SUCCESS; } // --------------------------------------------------------------------------------------------------------------- // Launch the app for the current worker DEFINE_SYSCALL
{ app_manager_put_launch_app_event(&(AppLaunchEventConfig) { .id = worker_manager_get_task_context()->install_id, .common.reason = APP_LAUNCH_WORKER, }); }
(void, sys_launch_app_for_worker, void)
<|repo_name|>pebble <|file_sep|>src/fw/syscall/app_worker_syscalls.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "applib/app_worker.h" #include "kernel/event_loop.h" #include "kernel/ui/modals/modal_manager.h" #include "kernel/ui/modals/modal_manager_private.h" #include "process_management/worker_manager.h" #include "process_management/app_manager.h" #include "popups/switch_worker_ui.h" #include "syscall/syscall_internal.h" // --------------------------------------------------------------------------------------------------------------- // Determine if the worker for the current app is running DEFINE_SYSCALL(bool, sys_app_worker_is_running, void) { const PebbleProcessMd *md = worker_manager_get_current_worker_md(); if (md == NULL) { return false; } return (uuid_equal(&md->uuid, &app_manager_get_current_app_md()->uuid)); } // --------------------------------------------------------------------------------------------------------------- // Display the confirmation dialog for switching into the worker static void prv_switch_worker(void *data) { AppInstallId install_id = (AppInstallId)data; WindowStack *window_stack = modal_manager_get_window_stack(ModalPriorityGeneric); switch_worker_confirm(install_id, false /* do not set as default */, window_stack); } // Launch the worker for the current app DEFINE_SYSCALL(AppWorkerResult, sys_app_worker_launch, void) { AppInstallId install_id = app_manager_get_task_context()->install_id; // Make sure there is a worker for this app if (!app_manager_get_task_context()->app_md->has_worker) { return APP_WORKER_RESULT_NO_WORKER; } // Is there a worker already running? const PebbleProcessMd *md = worker_manager_get_current_worker_md(); if (md != NULL) { const PebbleProcessMd *app_process = app_manager_get_current_app_md(); if (uuid_equal(&md->uuid, &app_process->uuid)) { return APP_WORKER_RESULT_ALREADY_RUNNING; } // We have to get confirmation first that it is OK to launch the new worker launcher_task_add_callback(prv_switch_worker, (void *) install_id); return APP_WORKER_RESULT_ASKING_CONFIRMATION; } worker_manager_put_launch_worker_event(install_id); worker_manager_set_default_install_id(install_id); return APP_WORKER_RESULT_SUCCESS; } // --------------------------------------------------------------------------------------------------------------- // Kill the worker for the current app DEFINE_SYSCALL(AppWorkerResult, sys_app_worker_kill, void) { const PebbleProcessMd *md = worker_manager_get_current_worker_md(); if (md == NULL) { return APP_WORKER_RESULT_NOT_RUNNING; } if (!uuid_equal(&md->uuid, &app_manager_get_current_app_md()->uuid)) { return APP_WORKER_RESULT_DIFFERENT_APP; } process_manager_put_kill_process_event(PebbleTask_Worker, true /*graceful*/); return APP_WORKER_RESULT_SUCCESS; } // --------------------------------------------------------------------------------------------------------------- // Launch the app for the current worker DEFINE_SYSCALL<|fim_suffix|> { app_manager_put_launch_app_event(&(AppLaunchEventConfig) { .id = worker_manager_get_task_context()->install_id, .common.reason = APP_LAUNCH_WORKER, }); } <|fim_middle|>(void, sys_launch_app_for_worker, void)<|endoftext|>
masked_node
argument_list
tests/fw/applib/test_app_message.c
ed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "clar.h" #include "applib/app_message/app_message_internal.h" #include "kernel/events.h" #include "system/logging.h" #include "util/attributes.h" #include "util/math.h" #include <stddef.h> #include <limits.h> extern AppTimer *app_message_outbox_get_ack_nack_timer(void); // Stubs //////////////////////////////////// #include "stubs_logging.h" #include "stubs_passert.h" #include "stubs_rand_ptr.h" #include "fake_pbl_malloc.h" // Fakes //////////////////////////////////// #include "fake_app_timer.h" #include "fake_pebble_tasks.h" // Structures and Externs //////////////////////////////////// typedef struct PACKED { AppMessageCmd command:8; uint8_t transaction_id; union PACKED { struct PACKED { Uuid uuid; Dictionary dictionary; //!< Variable length! } push; //!< valid for CMD_PUSH only struct PACKED {} ack; } payload[]; } AppMessage; extern AppTimer *app_message_ack_timer_id(void); extern bool app_message_is_accepting_inbound(void); extern bool app_message_is_accepting_outbound(void); extern bool app_message_is_closed_inbound(void); extern bool app_message_is_closed_outbound(void); extern void app_message_monitor_reset(void); // Globals //////////////////////////////////// static const uint16_t ENDPOINT_ID = 0x30; static const uint16_t MAX_SIZE_INBOUND = 32; static const uint16_t MAX_SIZE_OUTBOUND = 32; static const char *TEST_DATA = "01234567890123456789012345678901234567890123456789" "0123456789012345678901234567890123456789"; static const uint32_t TEST_KEY = 0xbeefbabe; static const uint8_t TEST_TRANSACTION_ID_1 = 0x11; // msgs with this ID are asserted to be ack'd static const uint8_t TEST_TRANSACTION_ID_2 = 0x22; // msgs with this ID are asserted to be nack'd static const uint16_t MAX_DATA_SIZE = MAX_SIZE_OUTBOUND - sizeof(Dictionary) - sizeof(Tuple); static int s_context; static DictionaryIterator s_expected_iter; uint8_t s_expected_buffer[MAX_SIZE_OUTBOUND]; static int s_out_sent_call_count = 0; static int s_out_failed_call_count = 0; static AppMessageResult s_failure_result = APP_MSG_OK; static bool s_ack_sent_is_called = false; static bool s_nack_sent_is_called = false; static bool s_in_received_is_called = false; static bool s_in_dropped_is_called = false; static bool s_ack_received_for_id_1 = false; static bool s_nack_received_for_id_2 = false; static AppMessageResult s_dropped_reason = APP_MSG_OK; static AppMessageCtx s_app_message_ctx; typedef void (*RemoteReceiveHandler)(uint16_t endpoint_id, const uint8_t* data, unsigned int length); static RemoteReceiveHandler s_remote_receive_handler; // UUID: 6bf6215b-c97f-409e-8c31-4f55657222b4 static Uuid simplicity_uuid = (Uuid){ 0x6b, 0xf6, 0x21, 0x5b, 0xc9, 0x7f, 0x40, 0x9e, 0x8c, 0x31, 0x4f, 0x55, 0x65, 0x72, 0x22, 0xb4 }; static CommSession *s_fake_app_comm_session = (CommSession *) 0xaabbccdd; static bool s_is_connected; static bool s_is_app_message_receiver_open; static Uuid s_app_uuid; static Uuid s_remote_app_uuid; static bool s_app_receiver_oom; // Utils //////////////////////////////////// static void prv_set_app_uuid(Uuid uuid) { s_app_uuid = uuid; } static void prv_set_remote_app_uuid(Uuid uuid) { s_remote_app_uuid = uuid; } //! @note Assumes same order of tuples in both dictionaries! static void prv_assert_dict_equal(DictionaryIterator *a, DictionaryIterator *b) { Tuple *a_tuple = dict_read_first(a); Tuple *b_tuple = dict_read_first(b); while (b_tuple && a_tuple) { cl_assert_equal_i(a_tuple->key, b_tuple->key); cl_assert_equal_i(a_tuple->length, b_tuple->length); cl_assert_equal_i(a_tuple->type, b_tuple->type); cl_assert_equal_m(a_tuple->value, b_tuple->value, a_tuple->length); a_tuple = dict_read_next(a); b_tuple = dict_read_next(b); } if (b_tuple) { cl_fail
; } else if (a_tuple) { cl_fail("Dictionary `A` contained more tuples than dictionary `B`."); } } // Callbacks //////////////////////////////////// static void prv_out_sent_callback(DictionaryIterator *sent, void *context) { s_out_sent_call_count++; cl_assert_equal_p(context, &s_context); prv_assert_dict_equal(sent, &s_expected_iter); // When the outbox sent callback is called, the outbox should be in the // ACCEPTING state again. cl_assert_equal_b(app_message_is_accepting_outbound(), true); } static void prv_out_failed_callback(DictionaryIterator *failed, AppMessageResult reason, void *context) { s_out_failed_call_count++; cl_assert_equal_p(context, &s_context); prv_assert_dict_equal(failed, &s_expected_iter); s_failure_result = reason; // When the outbox failed callback is called, the outbox should be in the // ACCEPTING state again. cl_assert_equal_b(app_message_is_accepting_outbound(), true); } static void prv_in_received_callback(DictionaryIterator *received, void *context) { cl_assert_equal_p(context, &s_context); prv_assert_dict_equal(received, &s_expected_iter); s_in_received_is_called = true; } static void prv_in_dropped_callback(AppMessageResult reason, void *context) { cl_assert_equal_p(context, &s_context); cl_assert_equal_b(s_in_dropped_is_called, false); s_in_dropped_is_called = true; s_dropped_reason = reason; } static void prv_send_ack_nack(uint16_t endpoint_id, const uint8_t* data, unsigned int length, bool nack) { const int o = offsetof(AppMessage, payload[0].push.dictionary); cl_assert_equal_i(length, o + dict_calc_buffer_size(1, MAX_DATA_SIZE)); CommSession *session = s_fake_app_comm_session; AppMessage *message = (AppMessage*)data; AppMessage ack = { .command = nack ? CMD_NACK : CMD_ACK, .transaction_id = message->transaction_id, }; if (endpoint_id == ENDPOINT_ID) { app_message_app_protocol_msg_callback(session, (const uint8_t*)&ack, sizeof(AppMessage), NULL); } else { cl_fail("Unhandled endpoint"); } } static void prv_nack_sent_callback(uint16_t endpoint_id, const uint8_t* data, unsigned int length) { s_nack_sent_is_called = true; prv_send_ack_nack(endpoint_id, data, length, true); } static void prv_ack_sent_callback(uint16_t endpoint_id, const uint8_t* data, unsigned int length) { s_ack_sent_is_called = true; prv_send_ack_nack(endpoint_id, data, length, false); } static void prv_receive_test_data(uint8_t transaction_id, const bool oversized) { const uint16_t dict_length = dict_calc_buffer_size(1, MAX_DATA_SIZE); const uint16_t message_length = offsetof(AppMessage, payload[0].push.dictionary) + + dict_length + (oversized ? 20 : 0); uint8_t buffer[message_length]; AppMessage *message = (AppMessage*)buffer; message->command = CMD_PUSH; message->transaction_id = transaction_id; message->payload->push.uuid = s_remote_app_uuid; memcpy(&message->payload->push.dictionary, s_expected_buffer, dict_length); PBL_LOG(LOG_LEVEL_DEBUG, "message->transaction_id = %"PRIu32, message->transaction_id); CommSession *session = s_fake_app_comm_session; app_message_app_protocol_msg_callback(session, buffer, message_length, NULL); } static void prv_receive_ack_nack_callback(uint16_t endpoint_id, const uint8_t* data, unsigned int length) { AppMessage *message = (AppMessage*)data; cl_assert(length == sizeof(AppMessage)); PBL_LOG(LOG_LEVEL_DEBUG, "message %"PRIu32", id1 %"PRIu32", id2 %"PRIu32, message->transaction_id, TEST_TRANSACTION_ID_1, TEST_TRANSACTION_ID_2); if (message->transaction_id == TEST_TRANSACTION_ID_1) { cl_assert_equal_b(s_ack_received_for_id_1, false); s_ack_received_for_id_1 = true; cl_assert_equal_i(message->command, CMD_ACK); } else if (message->transaction_id == TEST_TRANSACTION_ID_2) { cl_assert_equal_b(s_nack_received_for_id_2, false); s_nack_received_for_id_2 = true; cl_assert_equal_i(message->command, CMD_NACK); } else { cl_assert(false); } } static void prv_no_reply_ca
("Dictionary `B` contained more tuples than dictionary `A`.")
<|repo_name|>pebble <|file_sep|>tests/fw/applib/test_app_message.c <|fim_prefix|>ed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "clar.h" #include "applib/app_message/app_message_internal.h" #include "kernel/events.h" #include "system/logging.h" #include "util/attributes.h" #include "util/math.h" #include <stddef.h> #include <limits.h> extern AppTimer *app_message_outbox_get_ack_nack_timer(void); // Stubs //////////////////////////////////// #include "stubs_logging.h" #include "stubs_passert.h" #include "stubs_rand_ptr.h" #include "fake_pbl_malloc.h" // Fakes //////////////////////////////////// #include "fake_app_timer.h" #include "fake_pebble_tasks.h" // Structures and Externs //////////////////////////////////// typedef struct PACKED { AppMessageCmd command:8; uint8_t transaction_id; union PACKED { struct PACKED { Uuid uuid; Dictionary dictionary; //!< Variable length! } push; //!< valid for CMD_PUSH only struct PACKED {} ack; } payload[]; } AppMessage; extern AppTimer *app_message_ack_timer_id(void); extern bool app_message_is_accepting_inbound(void); extern bool app_message_is_accepting_outbound(void); extern bool app_message_is_closed_inbound(void); extern bool app_message_is_closed_outbound(void); extern void app_message_monitor_reset(void); // Globals //////////////////////////////////// static const uint16_t ENDPOINT_ID = 0x30; static const uint16_t MAX_SIZE_INBOUND = 32; static const uint16_t MAX_SIZE_OUTBOUND = 32; static const char *TEST_DATA = "01234567890123456789012345678901234567890123456789" "0123456789012345678901234567890123456789"; static const uint32_t TEST_KEY = 0xbeefbabe; static const uint8_t TEST_TRANSACTION_ID_1 = 0x11; // msgs with this ID are asserted to be ack'd static const uint8_t TEST_TRANSACTION_ID_2 = 0x22; // msgs with this ID are asserted to be nack'd static const uint16_t MAX_DATA_SIZE = MAX_SIZE_OUTBOUND - sizeof(Dictionary) - sizeof(Tuple); static int s_context; static DictionaryIterator s_expected_iter; uint8_t s_expected_buffer[MAX_SIZE_OUTBOUND]; static int s_out_sent_call_count = 0; static int s_out_failed_call_count = 0; static AppMessageResult s_failure_result = APP_MSG_OK; static bool s_ack_sent_is_called = false; static bool s_nack_sent_is_called = false; static bool s_in_received_is_called = false; static bool s_in_dropped_is_called = false; static bool s_ack_received_for_id_1 = false; static bool s_nack_received_for_id_2 = false; static AppMessageResult s_dropped_reason = APP_MSG_OK; static AppMessageCtx s_app_message_ctx; typedef void (*RemoteReceiveHandler)(uint16_t endpoint_id, const uint8_t* data, unsigned int length); static RemoteReceiveHandler s_remote_receive_handler; // UUID: 6bf6215b-c97f-409e-8c31-4f55657222b4 static Uuid simplicity_uuid = (Uuid){ 0x6b, 0xf6, 0x21, 0x5b, 0xc9, 0x7f, 0x40, 0x9e, 0x8c, 0x31, 0x4f, 0x55, 0x65, 0x72, 0x22, 0xb4 }; static CommSession *s_fake_app_comm_session = (CommSession *) 0xaabbccdd; static bool s_is_connected; static bool s_is_app_message_receiver_open; static Uuid s_app_uuid; static Uuid s_remote_app_uuid; static bool s_app_receiver_oom; // Utils //////////////////////////////////// static void prv_set_app_uuid(Uuid uuid) { s_app_uuid = uuid; } static void prv_set_remote_app_uuid(Uuid uuid) { s_remote_app_uuid = uuid; } //! @note Assumes same order of tuples in both dictionaries! static void prv_assert_dict_equal(DictionaryIterator *a, DictionaryIterator *b) { Tuple *a_tuple = dict_read_first(a); Tuple *b_tuple = dict_read_first(b); while (b_tuple && a_tuple) { cl_assert_equal_i(a_tuple->key, b_tuple->key); cl_assert_equal_i(a_tuple->length, b_tuple->length); cl_assert_equal_i(a_tuple->type, b_tuple->type); cl_assert_equal_m(a_tuple->value, b_tuple->value, a_tuple->length); a_tuple = dict_read_next(a); b_tuple = dict_read_next(b); } if (b_tuple) { cl_fail<|fim_suffix|>; } else if (a_tuple) { cl_fail("Dictionary `A` contained more tuples than dictionary `B`."); } } // Callbacks //////////////////////////////////// static void prv_out_sent_callback(DictionaryIterator *sent, void *context) { s_out_sent_call_count++; cl_assert_equal_p(context, &s_context); prv_assert_dict_equal(sent, &s_expected_iter); // When the outbox sent callback is called, the outbox should be in the // ACCEPTING state again. cl_assert_equal_b(app_message_is_accepting_outbound(), true); } static void prv_out_failed_callback(DictionaryIterator *failed, AppMessageResult reason, void *context) { s_out_failed_call_count++; cl_assert_equal_p(context, &s_context); prv_assert_dict_equal(failed, &s_expected_iter); s_failure_result = reason; // When the outbox failed callback is called, the outbox should be in the // ACCEPTING state again. cl_assert_equal_b(app_message_is_accepting_outbound(), true); } static void prv_in_received_callback(DictionaryIterator *received, void *context) { cl_assert_equal_p(context, &s_context); prv_assert_dict_equal(received, &s_expected_iter); s_in_received_is_called = true; } static void prv_in_dropped_callback(AppMessageResult reason, void *context) { cl_assert_equal_p(context, &s_context); cl_assert_equal_b(s_in_dropped_is_called, false); s_in_dropped_is_called = true; s_dropped_reason = reason; } static void prv_send_ack_nack(uint16_t endpoint_id, const uint8_t* data, unsigned int length, bool nack) { const int o = offsetof(AppMessage, payload[0].push.dictionary); cl_assert_equal_i(length, o + dict_calc_buffer_size(1, MAX_DATA_SIZE)); CommSession *session = s_fake_app_comm_session; AppMessage *message = (AppMessage*)data; AppMessage ack = { .command = nack ? CMD_NACK : CMD_ACK, .transaction_id = message->transaction_id, }; if (endpoint_id == ENDPOINT_ID) { app_message_app_protocol_msg_callback(session, (const uint8_t*)&ack, sizeof(AppMessage), NULL); } else { cl_fail("Unhandled endpoint"); } } static void prv_nack_sent_callback(uint16_t endpoint_id, const uint8_t* data, unsigned int length) { s_nack_sent_is_called = true; prv_send_ack_nack(endpoint_id, data, length, true); } static void prv_ack_sent_callback(uint16_t endpoint_id, const uint8_t* data, unsigned int length) { s_ack_sent_is_called = true; prv_send_ack_nack(endpoint_id, data, length, false); } static void prv_receive_test_data(uint8_t transaction_id, const bool oversized) { const uint16_t dict_length = dict_calc_buffer_size(1, MAX_DATA_SIZE); const uint16_t message_length = offsetof(AppMessage, payload[0].push.dictionary) + + dict_length + (oversized ? 20 : 0); uint8_t buffer[message_length]; AppMessage *message = (AppMessage*)buffer; message->command = CMD_PUSH; message->transaction_id = transaction_id; message->payload->push.uuid = s_remote_app_uuid; memcpy(&message->payload->push.dictionary, s_expected_buffer, dict_length); PBL_LOG(LOG_LEVEL_DEBUG, "message->transaction_id = %"PRIu32, message->transaction_id); CommSession *session = s_fake_app_comm_session; app_message_app_protocol_msg_callback(session, buffer, message_length, NULL); } static void prv_receive_ack_nack_callback(uint16_t endpoint_id, const uint8_t* data, unsigned int length) { AppMessage *message = (AppMessage*)data; cl_assert(length == sizeof(AppMessage)); PBL_LOG(LOG_LEVEL_DEBUG, "message %"PRIu32", id1 %"PRIu32", id2 %"PRIu32, message->transaction_id, TEST_TRANSACTION_ID_1, TEST_TRANSACTION_ID_2); if (message->transaction_id == TEST_TRANSACTION_ID_1) { cl_assert_equal_b(s_ack_received_for_id_1, false); s_ack_received_for_id_1 = true; cl_assert_equal_i(message->command, CMD_ACK); } else if (message->transaction_id == TEST_TRANSACTION_ID_2) { cl_assert_equal_b(s_nack_received_for_id_2, false); s_nack_received_for_id_2 = true; cl_assert_equal_i(message->command, CMD_NACK); } else { cl_assert(false); } } static void prv_no_reply_ca<|fim_middle|>("Dictionary `B` contained more tuples than dictionary `A`.")<|endoftext|>
masked_node
call_expression
src/bluetooth-fw/da1468x/host/advert.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <bluetooth/bt_driver_advert.h> #include <bluetooth/bluetooth_types.h> #include <string.h> #include <inttypes.h> #include "advert_state.h" #include "hc_protocol/hc_endpoint_advert.h" #include "hc_protocol/hc_protocol.h" #include "kernel/pbl_malloc.h" #include "system/logging.h" #include "ble_common.h" static bool prv_finish_request_response(HcProtocolMessage *request, HcProtocolMessage *resp, bool should_free_request) { bool rv = false; ble_error_t error = BLE_ERROR_FAILED; if (resp) { if (request->command_id == HcMessageID_Advert_Enable) { const HcAdvertEnableResponseData *data = (const HcAdvertEnableResponseData *)resp->payload; error = data->error; if (data->current_state != AdvertState_Running) { PBL_LOG(LOG_LEVEL_INFO, "State was 0x%x after advert enable", data->current_state); } } else { const ble_error_t *error_ptr = (const ble_error_t *)resp->payload; error = *error_ptr; } if (error == BLE_STATUS_OK) { rv = true; } else { PBL_LOG(LOG_LEVEL_ERROR, "Advert error: 0x%"PRIx8" for cmd: 0x%"PRIx8, error, request->command_id); } } else { PBL_LOG(LOG_LEVEL_ERROR, "Advert timeout for cmd: 0x%"PRIx8, request->command_id); } if (should_free_request) { kernel_free(request); } kernel_free(resp); return rv; } void bt_driver_advert_advertising_disable(void) { HcProtocolMessage request = { .message_length = sizeof(request), .endpoint_id = HcEndpointID_Advert, .command_id = HcMessageID_Advert_Disable, }; HcProtocolMessage *resp = hc_protocol_enqueue_and_expect(&request); prv_finish_request_response(&request, resp, false /* should_free_request */); } bool bt_driver_advert_client_get_tx_power(int8_t *tx_power) { // TODO PBL-34354: Must use ble_read_tx_power, but we don't know the connection index here. // Will have to figure out how to store and keep track of them. *tx_power = 0; return true; } void bt_driver_advert_set_advertising_data(const BLEAdData *ad_data) { const uint32_t ad_data_len = sizeof(BLEAdData) + ad_data->ad_data_length + ad_data->scan_resp_data_length; const uint32_t alloc_size = sizeof(HcProtocolMessage) + ad_data_len; HcProtocolMessage *request = kernel_malloc_check(alloc_size); *request = (HcProtocolMessage) { .message_length = alloc_size, .endpoint_id = HcEndpointID_Advert, .command_id = HcMessageID_Advert_SetAdvData, }; memcpy(request->payload, ad_data, ad_data_len); HcProtocolMessage *resp = hc_protocol_enqueue_and_expect(request);
; } bool bt_driver_advert_advertising_enable(uint32_t min_interval_ms, uint32_t max_interval_ms, bool enable_scan_resp) { const uint32_t alloc_size = sizeof(HcProtocolMessage) + sizeof(HcAdvertEnableData); HcProtocolMessage *request = kernel_malloc_check(alloc_size); *request = (HcProtocolMessage) { .message_length = alloc_size, .endpoint_id = HcEndpointID_Advert, .command_id = HcMessageID_Advert_Enable, }; HcAdvertEnableData *request_data = (HcAdvertEnableData *)&request->payload[0]; *request_data = (HcAdvertEnableData) { .min_interval_ms = min_interval_ms, .max_interval_ms = max_interval_ms, }; HcProtocolMessage *resp = hc_protocol_enqueue_and_expect(request); return prv_finish_request_response(request, resp, true /* should_free_request */); } // These are essentially stubs that were needed for bugs in another Bluetooth stack. bool bt_driver_advert_is_connectable(void) { return true; } bool bt_driver_advert_client_has_cycled(void) { return true; } void bt_driver_advert_client_set_cycled(bool has_cycled) { // nothing } bool bt_driver_advert_should_not_cycle(void) { return false; }
prv_finish_request_response(request, resp, true /* should_free_request */)
<|repo_name|>pebble <|file_sep|>src/bluetooth-fw/da1468x/host/advert.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <bluetooth/bt_driver_advert.h> #include <bluetooth/bluetooth_types.h> #include <string.h> #include <inttypes.h> #include "advert_state.h" #include "hc_protocol/hc_endpoint_advert.h" #include "hc_protocol/hc_protocol.h" #include "kernel/pbl_malloc.h" #include "system/logging.h" #include "ble_common.h" static bool prv_finish_request_response(HcProtocolMessage *request, HcProtocolMessage *resp, bool should_free_request) { bool rv = false; ble_error_t error = BLE_ERROR_FAILED; if (resp) { if (request->command_id == HcMessageID_Advert_Enable) { const HcAdvertEnableResponseData *data = (const HcAdvertEnableResponseData *)resp->payload; error = data->error; if (data->current_state != AdvertState_Running) { PBL_LOG(LOG_LEVEL_INFO, "State was 0x%x after advert enable", data->current_state); } } else { const ble_error_t *error_ptr = (const ble_error_t *)resp->payload; error = *error_ptr; } if (error == BLE_STATUS_OK) { rv = true; } else { PBL_LOG(LOG_LEVEL_ERROR, "Advert error: 0x%"PRIx8" for cmd: 0x%"PRIx8, error, request->command_id); } } else { PBL_LOG(LOG_LEVEL_ERROR, "Advert timeout for cmd: 0x%"PRIx8, request->command_id); } if (should_free_request) { kernel_free(request); } kernel_free(resp); return rv; } void bt_driver_advert_advertising_disable(void) { HcProtocolMessage request = { .message_length = sizeof(request), .endpoint_id = HcEndpointID_Advert, .command_id = HcMessageID_Advert_Disable, }; HcProtocolMessage *resp = hc_protocol_enqueue_and_expect(&request); prv_finish_request_response(&request, resp, false /* should_free_request */); } bool bt_driver_advert_client_get_tx_power(int8_t *tx_power) { // TODO PBL-34354: Must use ble_read_tx_power, but we don't know the connection index here. // Will have to figure out how to store and keep track of them. *tx_power = 0; return true; } void bt_driver_advert_set_advertising_data(const BLEAdData *ad_data) { const uint32_t ad_data_len = sizeof(BLEAdData) + ad_data->ad_data_length + ad_data->scan_resp_data_length; const uint32_t alloc_size = sizeof(HcProtocolMessage) + ad_data_len; HcProtocolMessage *request = kernel_malloc_check(alloc_size); *request = (HcProtocolMessage) { .message_length = alloc_size, .endpoint_id = HcEndpointID_Advert, .command_id = HcMessageID_Advert_SetAdvData, }; memcpy(request->payload, ad_data, ad_data_len); HcProtocolMessage *resp = hc_protocol_enqueue_and_expect(request); <|fim_suffix|>; } bool bt_driver_advert_advertising_enable(uint32_t min_interval_ms, uint32_t max_interval_ms, bool enable_scan_resp) { const uint32_t alloc_size = sizeof(HcProtocolMessage) + sizeof(HcAdvertEnableData); HcProtocolMessage *request = kernel_malloc_check(alloc_size); *request = (HcProtocolMessage) { .message_length = alloc_size, .endpoint_id = HcEndpointID_Advert, .command_id = HcMessageID_Advert_Enable, }; HcAdvertEnableData *request_data = (HcAdvertEnableData *)&request->payload[0]; *request_data = (HcAdvertEnableData) { .min_interval_ms = min_interval_ms, .max_interval_ms = max_interval_ms, }; HcProtocolMessage *resp = hc_protocol_enqueue_and_expect(request); return prv_finish_request_response(request, resp, true /* should_free_request */); } // These are essentially stubs that were needed for bugs in another Bluetooth stack. bool bt_driver_advert_is_connectable(void) { return true; } bool bt_driver_advert_client_has_cycled(void) { return true; } void bt_driver_advert_client_set_cycled(bool has_cycled) { // nothing } bool bt_driver_advert_should_not_cycle(void) { return false; } <|fim_middle|>prv_finish_request_response(request, resp, true /* should_free_request */)<|endoftext|>
prefix_only
call_expression
src/fw/services/normal/activity/health_util.c
tions under the License. */ #include "health_util.h" #include "services/common/i18n/i18n.h" #include "services/normal/activity/activity.h" #include "shell/prefs.h" #include "util/time/time.h" #include "util/units.h" #include "util/string.h" #include <limits.h> #include <stdio.h> #include <string.h> static void prv_convert_duration_to_hours_and_minutes(int duration_s, int *hours, int *minutes) { *hours = (duration_s / SECONDS_PER_HOUR) ?: INT_MIN; *minutes = ((duration_s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE) ?: INT_MIN; if (*minutes == INT_MIN && *hours == INT_MIN) { *hours = 0; } } int health_util_format_hours_and_minutes(char *buffer, size_t buffer_size, int duration_s, void *i18n_owner) { int hours; int minutes; prv_convert_duration_to_hours_and_minutes(duration_s, &hours, &minutes); int pos = 0; if (hours != INT_MIN) { pos += snprintf(buffer + pos, buffer_size - pos, i18n_get("%dH", i18n_owner), hours); if (minutes != INT_MIN && pos < (int)buffer_size - 1) { buffer[pos++] = ' '; } } if (minutes != INT_MIN) { pos += snprintf(buffer + pos, buffer_size - pos, i18n_get("%dM", i18n_owner), minutes); } return pos; } int health_util_format_hours_minutes_seconds(char *buffer, size_t buffer_size, int duration_s, bool leading_zero, void *i18n_owner) { const int hours = duration_s / SECONDS_PER_HOUR; const int minutes = (duration_s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE; const int seconds = (duration_s % SECONDS_PER_HOUR) % SECONDS_PER_MINUTE; if (hours > 0) { const char *fmt = leading_zero ? "%02d:%02d:%02d" : "%d:%02d:%02d"; return snprintf(buffer, buffer_size, i18n_get(fmt, i18n_owner), hours, minutes, seconds); } else { const char *fmt = leading_zero ? "%02d:%02d" : "%d:%02d"; return snprintf(buffer, buffer_size, i18n_get(fmt, i18n_owner), minutes, seconds); } } int health_util_format_minutes_and_seconds(char *buffer, size_t buffer_size, int duration_s, void *i18n_owner) { int minutes = duration_s / SECONDS_PER_MINUTE; int seconds = duration_s % SECONDS_PER_MINUTE; return snprintf(buffer, buffer_size, i18n_get("%d:%d", i18n_owner), minutes, seconds); } GTextNodeText *health_util_create_text_node(int buffer_size, GFont font, GColor color, GTextNodeContainer *container) { GTextNodeText *text_node = graphics_text_node_create_text(buffer_size); if (container) { graphics_text_node_container_add_child(container, &text_node->node); } text_node->font = font; text_node->color = color; return text_node; } GTextNodeText *health_util_create_text_node_with_text(const char *text, GFont font, GColor color, GTextNodeContainer *container) { GTextNodeText *text_node = health_util_create_text_node(0, font, color, container); text_node->text = text; return text_node; } void health_util_duration_to_hours_and_minutes_text_node(int duration_s, void *i18n_owner, GFont number_font, GFont units_font, GColor color, GTextNodeContainer *container) { int hours; int minutes; prv_convert_duration_to_hours_and_minutes(duration_s, &hours, &minutes); const int units_offset_y = fonts_get_font_height(number_font) - fonts_get_font_height(units_font); const int hours_and_minutes_buffer_size = sizeof("00"); if (hours != INT_MIN) { GTextNodeText *hours_text_node = health_util_create_text_node(hours_and_minutes_buffer_size, number_font, color, container); snprintf((char *) hours_text_node->text, hours_and_minutes_buffer_size, i18n_get("%d", i18n_owner), hours); GTextNodeText *hours_units_text_node =
health_util_create_text_node_with_text( i18n_get("H", i18n_owner), units_font, color, container)
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/activity/health_util.c <|fim_prefix|>tions under the License. */ #include "health_util.h" #include "services/common/i18n/i18n.h" #include "services/normal/activity/activity.h" #include "shell/prefs.h" #include "util/time/time.h" #include "util/units.h" #include "util/string.h" #include <limits.h> #include <stdio.h> #include <string.h> static void prv_convert_duration_to_hours_and_minutes(int duration_s, int *hours, int *minutes) { *hours = (duration_s / SECONDS_PER_HOUR) ?: INT_MIN; *minutes = ((duration_s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE) ?: INT_MIN; if (*minutes == INT_MIN && *hours == INT_MIN) { *hours = 0; } } int health_util_format_hours_and_minutes(char *buffer, size_t buffer_size, int duration_s, void *i18n_owner) { int hours; int minutes; prv_convert_duration_to_hours_and_minutes(duration_s, &hours, &minutes); int pos = 0; if (hours != INT_MIN) { pos += snprintf(buffer + pos, buffer_size - pos, i18n_get("%dH", i18n_owner), hours); if (minutes != INT_MIN && pos < (int)buffer_size - 1) { buffer[pos++] = ' '; } } if (minutes != INT_MIN) { pos += snprintf(buffer + pos, buffer_size - pos, i18n_get("%dM", i18n_owner), minutes); } return pos; } int health_util_format_hours_minutes_seconds(char *buffer, size_t buffer_size, int duration_s, bool leading_zero, void *i18n_owner) { const int hours = duration_s / SECONDS_PER_HOUR; const int minutes = (duration_s % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE; const int seconds = (duration_s % SECONDS_PER_HOUR) % SECONDS_PER_MINUTE; if (hours > 0) { const char *fmt = leading_zero ? "%02d:%02d:%02d" : "%d:%02d:%02d"; return snprintf(buffer, buffer_size, i18n_get(fmt, i18n_owner), hours, minutes, seconds); } else { const char *fmt = leading_zero ? "%02d:%02d" : "%d:%02d"; return snprintf(buffer, buffer_size, i18n_get(fmt, i18n_owner), minutes, seconds); } } int health_util_format_minutes_and_seconds(char *buffer, size_t buffer_size, int duration_s, void *i18n_owner) { int minutes = duration_s / SECONDS_PER_MINUTE; int seconds = duration_s % SECONDS_PER_MINUTE; return snprintf(buffer, buffer_size, i18n_get("%d:%d", i18n_owner), minutes, seconds); } GTextNodeText *health_util_create_text_node(int buffer_size, GFont font, GColor color, GTextNodeContainer *container) { GTextNodeText *text_node = graphics_text_node_create_text(buffer_size); if (container) { graphics_text_node_container_add_child(container, &text_node->node); } text_node->font = font; text_node->color = color; return text_node; } GTextNodeText *health_util_create_text_node_with_text(const char *text, GFont font, GColor color, GTextNodeContainer *container) { GTextNodeText *text_node = health_util_create_text_node(0, font, color, container); text_node->text = text; return text_node; } void health_util_duration_to_hours_and_minutes_text_node(int duration_s, void *i18n_owner, GFont number_font, GFont units_font, GColor color, GTextNodeContainer *container) { int hours; int minutes; prv_convert_duration_to_hours_and_minutes(duration_s, &hours, &minutes); const int units_offset_y = fonts_get_font_height(number_font) - fonts_get_font_height(units_font); const int hours_and_minutes_buffer_size = sizeof("00"); if (hours != INT_MIN) { GTextNodeText *hours_text_node = health_util_create_text_node(hours_and_minutes_buffer_size, number_font, color, container); snprintf((char *) hours_text_node->text, hours_and_minutes_buffer_size, i18n_get("%d", i18n_owner), hours); GTextNodeText *hours_units_text_node = <|fim_suffix|><|fim_middle|>health_util_create_text_node_with_text( i18n_get("H", i18n_owner), units_font, color, container)<|endoftext|>
prefix_only
call_expression
tests/fw/services/test_app_cache.c
= 58, .size = 88644 }, // priority rank 45 { .id = 6, .priority = 57, .size = 269063 }, // priority rank 43 { .id = 7, .priority = 43, .size = 83456 }, // priority rank 32 { .id = 8, .priority = 29, .size = 233211 }, // priority rank 20 { .id = 9, .priority = 38, .size = 55766 }, // priority rank 26 { .id = 10, .priority = 19, .size = 28359 }, // priority rank 12 { .id = 11, .priority = 29, .size = 82909 }, // priority rank 21 { .id = 12, .priority = 53, .size = 132316 }, // priority rank 41 { .id = 13, .priority = 45, .size = 214356 }, // priority rank 35 { .id = 14, .priority = 47, .size = 258908 }, // priority rank 36 { .id = 15, .priority = 19, .size = 117885 }, // priority rank 11 { .id = 16, .priority = 42, .size = 167427 }, // priority rank 31 { .id = 17, .priority = 1, .size = 22644 }, // priority rank 2 { .id = 18, .priority = 30, .size = 33202 }, // priority rank 22 { .id = 19, .priority = 25, .size = 151434 }, // priority rank 18 { .id = 20, .priority = 33, .size = 102321 }, // priority rank 24 { .id = 21, .priority = 19, .size = 223352 }, // priority rank 9 { .id = 22, .priority = 36, .size = 133221 }, // priority rank 25 { .id = 23, .priority = 51, .size = 169128 }, // priority rank 39 { .id = 24, .priority = 22, .size = 103055 }, // priority rank 14 { .id = 25, .priority = 44, .size = 182304 }, // priority rank 33 { .id = 26, .priority = 2, .size = 177430 }, // priority rank 3 { .id = 27, .priority = 5, .size = 248430 }, // priority rank 4 { .id = 28, .priority = 44, .size = 168622 }, // priority rank 34 { .id = 29, .priority = 6, .size = 192857 }, // priority rank 5 { .id = 30, .priority = 19, .size = 183331 }, // priority rank 10 { .id = 31, .priority = 61, .size = 111155 }, // priority rank 50 { .id = 32, .priority = 42, .size = 211695 }, // priority rank 30 { .id = 33, .priority = 49, .size = 35653 }, // priority rank 38 { .id = 34, .priority = 57, .size = 11541 }, // priority rank 44 { .id = 35, .priority = 40, .size = 49368 }, // priority rank 29 { .id = 36, .priority = 25, .size = 230982 }, // priority rank 17 { .id = 37, .priority = 32, .size = 185018 }, // priority rank 23 { .id = 38, .priority = 39, .size = 163897 }, // priority rank 27 { .id = 39, .priority = 24, .size = 233217 }, // priority rank 16 { .id = 40, .priority = 8, .size = 23717 }, // priority rank 6 { .id = 41, .priority = 61, .size = 266668 }, // priority rank 49 { .id = 42, .priority = 58, .size = 61228 }, // priority rank 46 { .id = 43, .priority = 12, .size = 23513 }, // priority rank 7 { .id = 44, .priority = 60, .size = 267049 }, // priority rank 47 { .id = 45, .priority = 52, .size = 240086 }, // priority rank 40 { .id = 46, .priority = 14, .size = 194481 }, // priority rank 8 { .id = 47, .priority = 27, .size = 42163 }, // priority rank 19 { .id = 48, .priority = 56, .size = 72854 }, // priority rank 42 { .id = 49, .priority = 49, .size = 217548 }, // priority rank 37 { .id = 50, .priority = 1, .size = 207357 }, // priority rank 1 }; extern uint32_t app_cache_get_size(void); void prv_load_lotta_apps(void) { for (int i = 0; i < 50; i++) { // time is the basis of the priority. Set the time so we know what priority. rtc_set_time(t_data[i].priority); cl_assert_equal_i(S_SUCCESS, app_cache_add_entry(t_data[i].id, t_data[i].size)); cl_assert_equal_i(S_SUCCESS, app_cache_app_launched(t_data[i].id)); // increment time so everything won't happen in the same second } for (int i = 0; i < 50; i++) { cl_assert_equal_b(true, app_cache_entry_exists(t_data[i].id)); } cl_assert_equal_i(SIZE_SUM, app_cache_get_size()); } void prv_cleanup(void) { app_cache_flush(); prv_load_lotta_apps(); } void test_app_cache__free_up_space_lots_apps(void) { uint32_t to_free; uint32_t before_size; uint32_t after_size; // test random number prv_cleanup(); to_free = 150000; before_size = app_cache_get_size(); cl_assert(before_size >= to_free); cl_assert_equal_i(S_SUCCESS,
app_cache_free_up_space(to_free)
<|repo_name|>pebble <|file_sep|>tests/fw/services/test_app_cache.c <|fim_prefix|>= 58, .size = 88644 }, // priority rank 45 { .id = 6, .priority = 57, .size = 269063 }, // priority rank 43 { .id = 7, .priority = 43, .size = 83456 }, // priority rank 32 { .id = 8, .priority = 29, .size = 233211 }, // priority rank 20 { .id = 9, .priority = 38, .size = 55766 }, // priority rank 26 { .id = 10, .priority = 19, .size = 28359 }, // priority rank 12 { .id = 11, .priority = 29, .size = 82909 }, // priority rank 21 { .id = 12, .priority = 53, .size = 132316 }, // priority rank 41 { .id = 13, .priority = 45, .size = 214356 }, // priority rank 35 { .id = 14, .priority = 47, .size = 258908 }, // priority rank 36 { .id = 15, .priority = 19, .size = 117885 }, // priority rank 11 { .id = 16, .priority = 42, .size = 167427 }, // priority rank 31 { .id = 17, .priority = 1, .size = 22644 }, // priority rank 2 { .id = 18, .priority = 30, .size = 33202 }, // priority rank 22 { .id = 19, .priority = 25, .size = 151434 }, // priority rank 18 { .id = 20, .priority = 33, .size = 102321 }, // priority rank 24 { .id = 21, .priority = 19, .size = 223352 }, // priority rank 9 { .id = 22, .priority = 36, .size = 133221 }, // priority rank 25 { .id = 23, .priority = 51, .size = 169128 }, // priority rank 39 { .id = 24, .priority = 22, .size = 103055 }, // priority rank 14 { .id = 25, .priority = 44, .size = 182304 }, // priority rank 33 { .id = 26, .priority = 2, .size = 177430 }, // priority rank 3 { .id = 27, .priority = 5, .size = 248430 }, // priority rank 4 { .id = 28, .priority = 44, .size = 168622 }, // priority rank 34 { .id = 29, .priority = 6, .size = 192857 }, // priority rank 5 { .id = 30, .priority = 19, .size = 183331 }, // priority rank 10 { .id = 31, .priority = 61, .size = 111155 }, // priority rank 50 { .id = 32, .priority = 42, .size = 211695 }, // priority rank 30 { .id = 33, .priority = 49, .size = 35653 }, // priority rank 38 { .id = 34, .priority = 57, .size = 11541 }, // priority rank 44 { .id = 35, .priority = 40, .size = 49368 }, // priority rank 29 { .id = 36, .priority = 25, .size = 230982 }, // priority rank 17 { .id = 37, .priority = 32, .size = 185018 }, // priority rank 23 { .id = 38, .priority = 39, .size = 163897 }, // priority rank 27 { .id = 39, .priority = 24, .size = 233217 }, // priority rank 16 { .id = 40, .priority = 8, .size = 23717 }, // priority rank 6 { .id = 41, .priority = 61, .size = 266668 }, // priority rank 49 { .id = 42, .priority = 58, .size = 61228 }, // priority rank 46 { .id = 43, .priority = 12, .size = 23513 }, // priority rank 7 { .id = 44, .priority = 60, .size = 267049 }, // priority rank 47 { .id = 45, .priority = 52, .size = 240086 }, // priority rank 40 { .id = 46, .priority = 14, .size = 194481 }, // priority rank 8 { .id = 47, .priority = 27, .size = 42163 }, // priority rank 19 { .id = 48, .priority = 56, .size = 72854 }, // priority rank 42 { .id = 49, .priority = 49, .size = 217548 }, // priority rank 37 { .id = 50, .priority = 1, .size = 207357 }, // priority rank 1 }; extern uint32_t app_cache_get_size(void); void prv_load_lotta_apps(void) { for (int i = 0; i < 50; i++) { // time is the basis of the priority. Set the time so we know what priority. rtc_set_time(t_data[i].priority); cl_assert_equal_i(S_SUCCESS, app_cache_add_entry(t_data[i].id, t_data[i].size)); cl_assert_equal_i(S_SUCCESS, app_cache_app_launched(t_data[i].id)); // increment time so everything won't happen in the same second } for (int i = 0; i < 50; i++) { cl_assert_equal_b(true, app_cache_entry_exists(t_data[i].id)); } cl_assert_equal_i(SIZE_SUM, app_cache_get_size()); } void prv_cleanup(void) { app_cache_flush(); prv_load_lotta_apps(); } void test_app_cache__free_up_space_lots_apps(void) { uint32_t to_free; uint32_t before_size; uint32_t after_size; // test random number prv_cleanup(); to_free = 150000; before_size = app_cache_get_size(); cl_assert(before_size >= to_free); cl_assert_equal_i(S_SUCCESS, <|fim_suffix|><|fim_middle|>app_cache_free_up_space(to_free)<|endoftext|>
prefix_only
argument_list
tests/fw/services/test_wakeup.c
d test_wakeup__basic_checks(void) { WakeupId wakeup_id = 0; cl_assert_equal_i(sys_get_time(), 1388563200); sys_wakeup_cancel_all_for_app(); // Schedule a wakeup in 10 seconds wakeup_id = sys_wakeup_schedule(sys_get_time() + 10, 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), sys_get_time() + 10); // Cancel wakeup event sys_wakeup_delete(wakeup_id); cl_assert_equal_i(sys_wakeup_query(wakeup_id), E_DOES_NOT_EXIST); // Schedule again wakeup_id = sys_wakeup_schedule(sys_get_time() + 10, 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), sys_get_time() + 10); // Cancel all wakeup events sys_wakeup_cancel_all_for_app(); cl_assert_equal_i(sys_wakeup_query(wakeup_id), E_DOES_NOT_EXIST); } void test_wakeup__max_events(void) { WakeupId wakeup_id = 0; sys_wakeup_cancel_all_for_app(); // Schedule 8 (max), at 1 minute offsets, then fail on 9th for (int i = 1; i <= MAX_WAKEUP_EVENTS_PER_APP; i++) { wakeup_id = sys_wakeup_schedule(sys_get_time() + (i * WAKEUP_EVENT_WINDOW), 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), sys_get_time() + (i * WAKEUP_EVENT_WINDOW)); } // Test that the 9th wakeup event fails to schedule (E_DOES_NOT_EXIST) wakeup_id = sys_wakeup_schedule(sys_get_time() + ((MAX_WAKEUP_EVENTS_PER_APP + 1) * WAKEUP_EVENT_WINDOW), 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), E_DOES_NOT_EXIST); } void test_wakeup__gap(void) { WakeupId wakeup_id = 0; sys_wakeup_cancel_all_for_app(); // Schedule 1 event in a minute wakeup_id = sys_wakeup_schedule(sys_get_time() + WAKEUP_EVENT_WINDOW, 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), sys_get_time() + WAKEUP_EVENT_WINDOW); // Test that another event < 1 minute away fails to schedule (E_DOES_NOT_EXIST) wakeup_id = sys_wakeup_schedule(sys_get_time() + WAKEUP_EVENT_WINDOW + 59, 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), E_DOES_NOT_EXIST); // Test that another event < 1 minute away fails to schedule (E_DOES_NOT_EXIST) wakeup_id = sys_wakeup_schedule(sys_get_time() + 1, 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), E_DOES_NOT_EXIST); } // work around system_task_add_callback extern void wakeup_dispatcher_system_task(void *data); void test_wakeup__out_of_order_schedule(void) { const time_t start_time = sys_get_time(); sys_wakeup_cancel_all_for_app(); // Schedule a wakeup for 10 windows into the future time_t late_event = start_time + WAKEUP_EVENT_WINDOW * 10; WakeupId late_wakeup_id = sys_wakeup_schedule(late_event, 0, false); cl_assert_equal_i(sys_wakeup_query(late_wakeup_id), late_event); // Schedule a wakeup for 5 windows into the future time_t early_event = start_time + WAKEUP_EVENT_WINDOW * 5; WakeupId early_wakeup_id = sys_wakeup_schedule(early_event, 0, false); cl_assert_equal_i(sys_wakeup_query(early_wakeup_id), early_event); cl_assert_equal_i(early_wakeup_id, wakeup_get_next_scheduled()); // Set time 5 minutes into the future, early_event should fire rtc_set_time(early_event); // Force wakeup to check for current wakeup event. wakeup_enable(false); wakeup_enable(true); // Simulate the firing of the early event stub_new_timer_fire(wakeup_get_current()); wakeup_dispatcher_system_task((void *)(uintptr_t)early_wakeup_id); // Make sure early_wakeup_id not scheduled cl_assert_equal_i(sys_wakeup_query(early_wakeup_id), E_DOES_NOT_EXIST); cl_assert_equal_i(sys_wakeup_query(late_wakeup_id), late_event); // Make sure that the next scheduled timer is now the late wakeup id. cl_assert_equal_i(late_wakeup_id, wakeup_get_next_scheduled()); // Set time 10 minutes into the future, late_event should fire rtc_set_time(late_event); // Force wakeup to check for current wakeup event. wakeup_enable(false); wakeup_enable(true); // Simulate the firing of the late event stub_new_timer_fire(wakeup_get_current()); wakeup_dispatcher_system_task((void *)(uintptr_t)late_wakeup_id); // There should now be no scheduled wakeups cl_assert_equal_i(sys_wakeup_query
(late_wakeup_id)
<|repo_name|>pebble <|file_sep|>tests/fw/services/test_wakeup.c <|fim_prefix|>d test_wakeup__basic_checks(void) { WakeupId wakeup_id = 0; cl_assert_equal_i(sys_get_time(), 1388563200); sys_wakeup_cancel_all_for_app(); // Schedule a wakeup in 10 seconds wakeup_id = sys_wakeup_schedule(sys_get_time() + 10, 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), sys_get_time() + 10); // Cancel wakeup event sys_wakeup_delete(wakeup_id); cl_assert_equal_i(sys_wakeup_query(wakeup_id), E_DOES_NOT_EXIST); // Schedule again wakeup_id = sys_wakeup_schedule(sys_get_time() + 10, 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), sys_get_time() + 10); // Cancel all wakeup events sys_wakeup_cancel_all_for_app(); cl_assert_equal_i(sys_wakeup_query(wakeup_id), E_DOES_NOT_EXIST); } void test_wakeup__max_events(void) { WakeupId wakeup_id = 0; sys_wakeup_cancel_all_for_app(); // Schedule 8 (max), at 1 minute offsets, then fail on 9th for (int i = 1; i <= MAX_WAKEUP_EVENTS_PER_APP; i++) { wakeup_id = sys_wakeup_schedule(sys_get_time() + (i * WAKEUP_EVENT_WINDOW), 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), sys_get_time() + (i * WAKEUP_EVENT_WINDOW)); } // Test that the 9th wakeup event fails to schedule (E_DOES_NOT_EXIST) wakeup_id = sys_wakeup_schedule(sys_get_time() + ((MAX_WAKEUP_EVENTS_PER_APP + 1) * WAKEUP_EVENT_WINDOW), 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), E_DOES_NOT_EXIST); } void test_wakeup__gap(void) { WakeupId wakeup_id = 0; sys_wakeup_cancel_all_for_app(); // Schedule 1 event in a minute wakeup_id = sys_wakeup_schedule(sys_get_time() + WAKEUP_EVENT_WINDOW, 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), sys_get_time() + WAKEUP_EVENT_WINDOW); // Test that another event < 1 minute away fails to schedule (E_DOES_NOT_EXIST) wakeup_id = sys_wakeup_schedule(sys_get_time() + WAKEUP_EVENT_WINDOW + 59, 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), E_DOES_NOT_EXIST); // Test that another event < 1 minute away fails to schedule (E_DOES_NOT_EXIST) wakeup_id = sys_wakeup_schedule(sys_get_time() + 1, 0, false); cl_assert_equal_i(sys_wakeup_query(wakeup_id), E_DOES_NOT_EXIST); } // work around system_task_add_callback extern void wakeup_dispatcher_system_task(void *data); void test_wakeup__out_of_order_schedule(void) { const time_t start_time = sys_get_time(); sys_wakeup_cancel_all_for_app(); // Schedule a wakeup for 10 windows into the future time_t late_event = start_time + WAKEUP_EVENT_WINDOW * 10; WakeupId late_wakeup_id = sys_wakeup_schedule(late_event, 0, false); cl_assert_equal_i(sys_wakeup_query(late_wakeup_id), late_event); // Schedule a wakeup for 5 windows into the future time_t early_event = start_time + WAKEUP_EVENT_WINDOW * 5; WakeupId early_wakeup_id = sys_wakeup_schedule(early_event, 0, false); cl_assert_equal_i(sys_wakeup_query(early_wakeup_id), early_event); cl_assert_equal_i(early_wakeup_id, wakeup_get_next_scheduled()); // Set time 5 minutes into the future, early_event should fire rtc_set_time(early_event); // Force wakeup to check for current wakeup event. wakeup_enable(false); wakeup_enable(true); // Simulate the firing of the early event stub_new_timer_fire(wakeup_get_current()); wakeup_dispatcher_system_task((void *)(uintptr_t)early_wakeup_id); // Make sure early_wakeup_id not scheduled cl_assert_equal_i(sys_wakeup_query(early_wakeup_id), E_DOES_NOT_EXIST); cl_assert_equal_i(sys_wakeup_query(late_wakeup_id), late_event); // Make sure that the next scheduled timer is now the late wakeup id. cl_assert_equal_i(late_wakeup_id, wakeup_get_next_scheduled()); // Set time 10 minutes into the future, late_event should fire rtc_set_time(late_event); // Force wakeup to check for current wakeup event. wakeup_enable(false); wakeup_enable(true); // Simulate the firing of the late event stub_new_timer_fire(wakeup_get_current()); wakeup_dispatcher_system_task((void *)(uintptr_t)late_wakeup_id); // There should now be no scheduled wakeups cl_assert_equal_i(sys_wakeup_query<|fim_suffix|><|fim_middle|>(late_wakeup_id)<|endoftext|>
masked_node
argument_list
src/fw/applib/ui/scroll_layer.c
. in an update_proc) and would otherwise implicitly stop scroll animations. // It's fine to keep scroll animations running as they clip the offset to valid bounds. prv_scroll_layer_set_content_offset_internal( scroll_layer, scroll_layer_get_content_offset(scroll_layer)); } GSize scroll_layer_get_content_size(const ScrollLayer *scroll_layer) { return scroll_layer->content_sublayer.bounds.size; } void scroll_layer_scroll(ScrollLayer *scroll_layer, ScrollDirection direction, bool animated) { GPoint offset = scroll_layer_get_content_offset(scroll_layer); int32_t scroll_height = 32; // If process is 3.x and has enabled paging if (prv_scroll_layer_is_paging_enabled(scroll_layer)) { uint16_t page_height = prv_scroll_layer_get_paging_height(scroll_layer); if (page_height) { // Force offset to start (and stay) page aligned offset.y = ROUND_TO_MOD_CEIL(offset.y, page_height); scroll_height = page_height; } } switch (direction) { case ScrollDirectionUp: offset.y += scroll_height; break; case ScrollDirectionDown: offset.y -= scroll_height; break; default: return; } scroll_layer_set_content_offset(scroll_layer, offset, animated); } void scroll_layer_scroll_up_click_handler(ClickRecognizerRef recognizer, void *context) { ScrollLayer *scroll_layer = (ScrollLayer *)context; scroll_layer_scroll(scroll_layer, ScrollDirectionUp, true); (void)recognizer; } void scroll_layer_scroll_down_click_handler(ClickRecognizerRef recognizer, void *context) { ScrollLayer *scroll_layer = (ScrollLayer *)context; scroll_layer_scroll(scroll_layer, ScrollDirectionDown, true); (void)recognizer; } static void scroll_layer_click_config_provider(ScrollLayer *scroll_layer) { // Config UP / DOWN button behavior: window_single_repeating_click_subscribe(BUTTON_ID_UP, 100, scroll_layer_scroll_up_click_handler); window_single_repeating_click_subscribe(BUTTON_ID_DOWN, 100, scroll_layer_scroll_down_click_handler); // Set the context for the SELECT button: window_set_click_context(BUTTON_ID_SELECT, get_callback_context(scroll_layer)); // Callback to provide the client to setup the SELECT button: if (scroll_layer->callbacks.click_config_provider) { scroll_layer->callbacks.click_config_provider(get_callback_context(scroll_layer)); } } void scroll_layer_set_click_config_onto_window(ScrollLayer *scroll_layer, struct Window *window) { window_set_click_config_provider_with_context(window, (ClickConfigProvider) scroll_layer_click_config_provider, scroll_layer); } void scroll_layer_set_callbacks(ScrollLayer *scroll_layer, ScrollLayerCallbacks callbacks) { scroll_layer->callbacks = callbacks; } void scroll_layer_set_context(ScrollLayer *scroll_layer, void *context) { scroll_layer->context = context; } void scroll_layer_set_shadow_hidden(ScrollLayer *scroll_layer, bool hidden) { PBL_ASSERTN(scroll_layer); // paging and shadow_sublayer are mutually exclusive // so init shadow_sublayer if it was paging data if (prv_scroll_layer_is_paging_enabled(scroll_layer) && hidden == false) { prv_setup_shadow_layer(scroll_layer); } scroll_layer_property_changed_proc((Layer*)scroll_layer); layer_set_hidden(&scroll_layer->shadow_sublayer, hidden); } bool scroll_layer_get_shadow_hidden(const ScrollLayer *scroll_layer) { return layer_get_hidden(&scroll_layer->shadow_sublayer); } void scroll_layer_set_paging(ScrollLayer *scroll_layer, bool paging_enabled) { PBL_ASSERTN(scroll_layer); if (paging_enabled) { // Deinit shadow_sublayer to enable paging if (!prv_scroll_layer_is_paging_enabled(scroll_layer)) { layer_deinit(&scroll_layer->shadow_sublayer); } // paging and shadow_sublayer are mutually exclusive scroll_layer->paging.shadow_hidden = true; scroll_layer->paging.paging_disabled = false; } else { if (prv_scroll_layer_is_paging_enabled(scroll_layer)) { prv_setup_shadow_layer(scroll_layer); // still require explicit un-hiding of shadow scroll_layer_set_shadow_hidden
; } } } bool scroll_layer_get_paging(ScrollLayer* scroll_layer) { return scroll_layer && prv_scroll_layer_is_paging_enabled(scroll_layer); } ContentIndicator *scroll_layer_get_content_indicator(ScrollLayer *scroll_layer) { return content_indicator_get_or_create_for_scroll_layer(scroll_layer); } void scroll_layer_update_content_indicator(ScrollLayer *scroll_layer) { ContentIndicator *content_indicator = content_indicator_get_for_scroll_layer(scroll_layer); if (!content_indicator) { return; } const GSize scroll_layer_frame_size = scroll_layer_get_layer(scroll_layer)->frame.size; const GSize scroll_layer_content_size = scroll_layer_get_content_size(scroll_layer); const int16_t scroll_layer_content_offset_y = scroll_layer_get_content_offset(scroll_layer).y; const bool content_available_up = (scroll_layer_content_offset_y < 0); content_indicator_set_content_available(content_indicator, ContentIndicatorDirectionUp, content_available_up); const bool content_available_down = (scroll_layer_frame_size.h - scroll_layer_content_offset_y < scroll_layer_content_size.h); content_indicator_set_content_available(content_indicator, ContentIndicatorDirectionDown, content_available_down); } void scroll_layer_set_clips_content_offset(ScrollLayer *scroll_layer, bool clips) { scroll_layer->content_sublayer.clips = clips; scroll_layer_set_content_offset(scroll_layer, scroll_layer_get_content_offset(scroll_layer), false); } bool scroll_layer_get_clips_content_offset(ScrollLayer *scroll_layer) { return scroll_layer->content_sublayer.clips; }
(scroll_layer, true)
<|repo_name|>pebble <|file_sep|>src/fw/applib/ui/scroll_layer.c <|fim_prefix|>. in an update_proc) and would otherwise implicitly stop scroll animations. // It's fine to keep scroll animations running as they clip the offset to valid bounds. prv_scroll_layer_set_content_offset_internal( scroll_layer, scroll_layer_get_content_offset(scroll_layer)); } GSize scroll_layer_get_content_size(const ScrollLayer *scroll_layer) { return scroll_layer->content_sublayer.bounds.size; } void scroll_layer_scroll(ScrollLayer *scroll_layer, ScrollDirection direction, bool animated) { GPoint offset = scroll_layer_get_content_offset(scroll_layer); int32_t scroll_height = 32; // If process is 3.x and has enabled paging if (prv_scroll_layer_is_paging_enabled(scroll_layer)) { uint16_t page_height = prv_scroll_layer_get_paging_height(scroll_layer); if (page_height) { // Force offset to start (and stay) page aligned offset.y = ROUND_TO_MOD_CEIL(offset.y, page_height); scroll_height = page_height; } } switch (direction) { case ScrollDirectionUp: offset.y += scroll_height; break; case ScrollDirectionDown: offset.y -= scroll_height; break; default: return; } scroll_layer_set_content_offset(scroll_layer, offset, animated); } void scroll_layer_scroll_up_click_handler(ClickRecognizerRef recognizer, void *context) { ScrollLayer *scroll_layer = (ScrollLayer *)context; scroll_layer_scroll(scroll_layer, ScrollDirectionUp, true); (void)recognizer; } void scroll_layer_scroll_down_click_handler(ClickRecognizerRef recognizer, void *context) { ScrollLayer *scroll_layer = (ScrollLayer *)context; scroll_layer_scroll(scroll_layer, ScrollDirectionDown, true); (void)recognizer; } static void scroll_layer_click_config_provider(ScrollLayer *scroll_layer) { // Config UP / DOWN button behavior: window_single_repeating_click_subscribe(BUTTON_ID_UP, 100, scroll_layer_scroll_up_click_handler); window_single_repeating_click_subscribe(BUTTON_ID_DOWN, 100, scroll_layer_scroll_down_click_handler); // Set the context for the SELECT button: window_set_click_context(BUTTON_ID_SELECT, get_callback_context(scroll_layer)); // Callback to provide the client to setup the SELECT button: if (scroll_layer->callbacks.click_config_provider) { scroll_layer->callbacks.click_config_provider(get_callback_context(scroll_layer)); } } void scroll_layer_set_click_config_onto_window(ScrollLayer *scroll_layer, struct Window *window) { window_set_click_config_provider_with_context(window, (ClickConfigProvider) scroll_layer_click_config_provider, scroll_layer); } void scroll_layer_set_callbacks(ScrollLayer *scroll_layer, ScrollLayerCallbacks callbacks) { scroll_layer->callbacks = callbacks; } void scroll_layer_set_context(ScrollLayer *scroll_layer, void *context) { scroll_layer->context = context; } void scroll_layer_set_shadow_hidden(ScrollLayer *scroll_layer, bool hidden) { PBL_ASSERTN(scroll_layer); // paging and shadow_sublayer are mutually exclusive // so init shadow_sublayer if it was paging data if (prv_scroll_layer_is_paging_enabled(scroll_layer) && hidden == false) { prv_setup_shadow_layer(scroll_layer); } scroll_layer_property_changed_proc((Layer*)scroll_layer); layer_set_hidden(&scroll_layer->shadow_sublayer, hidden); } bool scroll_layer_get_shadow_hidden(const ScrollLayer *scroll_layer) { return layer_get_hidden(&scroll_layer->shadow_sublayer); } void scroll_layer_set_paging(ScrollLayer *scroll_layer, bool paging_enabled) { PBL_ASSERTN(scroll_layer); if (paging_enabled) { // Deinit shadow_sublayer to enable paging if (!prv_scroll_layer_is_paging_enabled(scroll_layer)) { layer_deinit(&scroll_layer->shadow_sublayer); } // paging and shadow_sublayer are mutually exclusive scroll_layer->paging.shadow_hidden = true; scroll_layer->paging.paging_disabled = false; } else { if (prv_scroll_layer_is_paging_enabled(scroll_layer)) { prv_setup_shadow_layer(scroll_layer); // still require explicit un-hiding of shadow scroll_layer_set_shadow_hidden<|fim_suffix|>; } } } bool scroll_layer_get_paging(ScrollLayer* scroll_layer) { return scroll_layer && prv_scroll_layer_is_paging_enabled(scroll_layer); } ContentIndicator *scroll_layer_get_content_indicator(ScrollLayer *scroll_layer) { return content_indicator_get_or_create_for_scroll_layer(scroll_layer); } void scroll_layer_update_content_indicator(ScrollLayer *scroll_layer) { ContentIndicator *content_indicator = content_indicator_get_for_scroll_layer(scroll_layer); if (!content_indicator) { return; } const GSize scroll_layer_frame_size = scroll_layer_get_layer(scroll_layer)->frame.size; const GSize scroll_layer_content_size = scroll_layer_get_content_size(scroll_layer); const int16_t scroll_layer_content_offset_y = scroll_layer_get_content_offset(scroll_layer).y; const bool content_available_up = (scroll_layer_content_offset_y < 0); content_indicator_set_content_available(content_indicator, ContentIndicatorDirectionUp, content_available_up); const bool content_available_down = (scroll_layer_frame_size.h - scroll_layer_content_offset_y < scroll_layer_content_size.h); content_indicator_set_content_available(content_indicator, ContentIndicatorDirectionDown, content_available_down); } void scroll_layer_set_clips_content_offset(ScrollLayer *scroll_layer, bool clips) { scroll_layer->content_sublayer.clips = clips; scroll_layer_set_content_offset(scroll_layer, scroll_layer_get_content_offset(scroll_layer), false); } bool scroll_layer_get_clips_content_offset(ScrollLayer *scroll_layer) { return scroll_layer->content_sublayer.clips; } <|fim_middle|>(scroll_layer, true)<|endoftext|>
prefix_only
compound_statement
src/fw/services/normal/analytics/analytics_heartbeat.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "services/common/analytics/analytics_heartbeat.h" #include "services/common/analytics/analytics_metric.h" #include "services/common/analytics/analytics_logging.h" #include "system/logging.h" #include "system/passert.h" #include "kernel/pbl_malloc.h" #include "util/math.h" #include <inttypes.h> #include <stdio.h> uint32_t analytics_heartbeat_kind_data_size(AnalyticsHeartbeatKind kind) { AnalyticsMetric last = ANALYTICS_METRIC_INVALID; switch (kind) { case ANALYTICS_HEARTBEAT_KIND_DEVICE: last = ANALYTICS_DEVICE_METRIC_END - 1; break; case ANALYTICS_HEARTBEAT_KIND_APP: last = ANALYTICS_APP_METRIC_END - 1; break; } PBL_ASSERTN(last != ANALYTICS_METRIC_INVALID); return analytics_metric_offset(last) + analytics_metric_size(last); } ///////////////////// // Private static bool prv_verify_kinds_match(AnalyticsHeartbeat *heartbeat, AnalyticsMetric metric) { AnalyticsMetricKind metric_kind = analytics_metric_kind(metric); if ((metric_kind == ANALYTICS_METRIC_KIND_DEVICE) && (heartbeat->kind == ANALYTICS_HEARTBEAT_KIND_DEVICE)) { return true; } else if ((metric_kind == ANALYTICS_METRIC_KIND_APP) && (heartbeat->kind == ANALYTICS_HEARTBEAT_KIND_APP)) { return true; } else { PBL_CROAK("Metric kind does not match heartbeat kind! %d %d", metric_kind, heartbeat->kind); } } static uint8_t *prv_heartbeat_get_location(AnalyticsHeartbeat *heartbeat, AnalyticsMetric metric) { prv_verify_kinds_match(heartbeat, metric); if (analytics_metric_is_array(metric))
{ PBL_CROAK("Attempt to use integer value for array metric."); }
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/analytics/analytics_heartbeat.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "services/common/analytics/analytics_heartbeat.h" #include "services/common/analytics/analytics_metric.h" #include "services/common/analytics/analytics_logging.h" #include "system/logging.h" #include "system/passert.h" #include "kernel/pbl_malloc.h" #include "util/math.h" #include <inttypes.h> #include <stdio.h> uint32_t analytics_heartbeat_kind_data_size(AnalyticsHeartbeatKind kind) { AnalyticsMetric last = ANALYTICS_METRIC_INVALID; switch (kind) { case ANALYTICS_HEARTBEAT_KIND_DEVICE: last = ANALYTICS_DEVICE_METRIC_END - 1; break; case ANALYTICS_HEARTBEAT_KIND_APP: last = ANALYTICS_APP_METRIC_END - 1; break; } PBL_ASSERTN(last != ANALYTICS_METRIC_INVALID); return analytics_metric_offset(last) + analytics_metric_size(last); } ///////////////////// // Private static bool prv_verify_kinds_match(AnalyticsHeartbeat *heartbeat, AnalyticsMetric metric) { AnalyticsMetricKind metric_kind = analytics_metric_kind(metric); if ((metric_kind == ANALYTICS_METRIC_KIND_DEVICE) && (heartbeat->kind == ANALYTICS_HEARTBEAT_KIND_DEVICE)) { return true; } else if ((metric_kind == ANALYTICS_METRIC_KIND_APP) && (heartbeat->kind == ANALYTICS_HEARTBEAT_KIND_APP)) { return true; } else { PBL_CROAK("Metric kind does not match heartbeat kind! %d %d", metric_kind, heartbeat->kind); } } static uint8_t *prv_heartbeat_get_location(AnalyticsHeartbeat *heartbeat, AnalyticsMetric metric) { prv_verify_kinds_match(heartbeat, metric); if (analytics_metric_is_array(metric)) <|fim_suffix|><|fim_middle|>{ PBL_CROAK("Attempt to use integer value for array metric."); }<|endoftext|>
masked_node
compound_statement
src/fw/applib/graphics/gbitmap_sequence.c
nd_over(src, dst); } else { *dst = src; } } } } else if (png_format >= UPNG_LUMINANCE1 && png_format <= UPNG_LUMINANCE8) { const int32_t transparent_gray = gbitmap_png_get_transparent_gray_value(upng); for (uint32_t y = 0; y < fctl.height; y++) { const uint16_t corrected_y = fctl.y_offset + y + bitmap->bounds.origin.y; const GBitmapDataRowInfo row_info = gbitmap_get_data_row_info(bitmap, corrected_y); // delta_x is the first bit of data in this frame relative to the bitmap's coordinate system const int16_t delta_x = fctl.x_offset + bitmap->bounds.origin.x; // for each pixel in this frame, clipping to the bitmap geometry for (int32_t x = MAX(0, row_info.min_x - delta_x); x < MIN((int32_t)fctl.width, row_info.max_x - delta_x + 1); x++) { const uint32_t corrected_dst_x = x + delta_x; uint8_t channel = raw_image_get_value_for_bitdepth(upng_buffer, x, y, row_stride_bytes, bpp); if (transparent_gray >= 0 && channel == transparent_gray) { // Grayscale only has fully transparent, so only modify pixels // during OP_SOURCE to make the area transparent if (fctl.blend_op == APNG_BLEND_OP_SOURCE) { prv_set_pixel_in_row(row_info.data, bitmap_format, corrected_dst_x, GColorClear); } } else { channel = (channel * 255) / ~(~0 << bpp); // Convert to 8-bit value const GColor8 color = GColorFromRGB(channel, channel, channel); prv_set_pixel_in_row(row_info.data, bitmap_format, corrected_dst_x, color); } } } } // Successfully updated gbitmap from sequence retval = true; cleanup: if (!retval) { APP_LOG(APP_LOG_LEVEL_ERROR, APNG_UPDATE_ERROR); applib_free(buffer); } return retval; } // total elapsed from start of animation bool gbitmap_sequence_update_bitmap_by_elapsed(GBitmapSequence *bitmap_sequence, GBitmap *bitmap, uint32_t elapsed_ms) { if (!bitmap_sequence) { return false; } // Disabled if play count is 0 and not the very first frame if (bitmap_sequence->play_count == 0 && bitmap_sequence->current_frame != 0) { return false; } // If animation has started and specified time is in the past if (bitmap_sequence->current_frame_delay_ms != 0 && elapsed_ms <= bitmap_sequence->elapsed_ms) { APP_LOG(APP_LOG_LEVEL_WARNING, APNG_ELAPSED_WARNING); return false; } bool retval = false; bool frame_updated = true; while (frame_updated && ((elapsed_ms > bitmap_sequence->elapsed_ms) || (bitmap_sequence->current_frame_delay_ms == 0))) { frame_updated = gbitmap_sequence_update_bitmap_next_frame(bitmap_sequence, bitmap, NULL); // If frame is updated at least once, return true if (frame_updated) { retval = true; } } return retval; } // Helper functions int32_t gbitmap_sequence_get_current_frame_idx(GBitmapSequence *bitmap_sequence) { if (bitmap_sequence) { return bitmap_sequence->current_frame; } return -1; } uint32_t gbitmap_sequence_get_current_frame_delay_ms(GBitmapSequence *bitmap_sequence) { if (bitmap_sequence) { return bitmap_sequence->current_frame_delay_ms; } return 0; } uint32_t gbitmap_sequence_get_total_num_frames(GBitmapSequence *bitmap_sequence) { if (bitmap_sequence) { return bitmap_sequence->total_frames; } return 0; } uint32_t gbitmap_sequence_get_play_count(GBitmapSequence *bitmap_sequence) { if (bitmap_sequence) { return bitmap_sequence->play_count; } return 0; } void gbitmap_sequence_set_play_count(GBitmapSequence *bitmap_sequence, uint32_t play_count) { // Loop count is not allowed to be set to 0 if (bitmap_sequence && play_count) { bitmap_sequence->play_count = play_count; } } GSize gbitmap_sequence_get_bitmap_size(GBitmapSequence *bitmap_sequence) { GSize size = (GSize){0, 0}; if (bitmap_sequence)
return size; } uint32_t gbitmap_sequence_get_total_duration(GBitmapSequence *bitmap_sequence) { if (bitmap_sequence) { return bitmap_sequence->total_duration_ms; } return 0; }
{ size = bitmap_sequence->bitmap_size; }
<|repo_name|>pebble <|file_sep|>src/fw/applib/graphics/gbitmap_sequence.c <|fim_prefix|>nd_over(src, dst); } else { *dst = src; } } } } else if (png_format >= UPNG_LUMINANCE1 && png_format <= UPNG_LUMINANCE8) { const int32_t transparent_gray = gbitmap_png_get_transparent_gray_value(upng); for (uint32_t y = 0; y < fctl.height; y++) { const uint16_t corrected_y = fctl.y_offset + y + bitmap->bounds.origin.y; const GBitmapDataRowInfo row_info = gbitmap_get_data_row_info(bitmap, corrected_y); // delta_x is the first bit of data in this frame relative to the bitmap's coordinate system const int16_t delta_x = fctl.x_offset + bitmap->bounds.origin.x; // for each pixel in this frame, clipping to the bitmap geometry for (int32_t x = MAX(0, row_info.min_x - delta_x); x < MIN((int32_t)fctl.width, row_info.max_x - delta_x + 1); x++) { const uint32_t corrected_dst_x = x + delta_x; uint8_t channel = raw_image_get_value_for_bitdepth(upng_buffer, x, y, row_stride_bytes, bpp); if (transparent_gray >= 0 && channel == transparent_gray) { // Grayscale only has fully transparent, so only modify pixels // during OP_SOURCE to make the area transparent if (fctl.blend_op == APNG_BLEND_OP_SOURCE) { prv_set_pixel_in_row(row_info.data, bitmap_format, corrected_dst_x, GColorClear); } } else { channel = (channel * 255) / ~(~0 << bpp); // Convert to 8-bit value const GColor8 color = GColorFromRGB(channel, channel, channel); prv_set_pixel_in_row(row_info.data, bitmap_format, corrected_dst_x, color); } } } } // Successfully updated gbitmap from sequence retval = true; cleanup: if (!retval) { APP_LOG(APP_LOG_LEVEL_ERROR, APNG_UPDATE_ERROR); applib_free(buffer); } return retval; } // total elapsed from start of animation bool gbitmap_sequence_update_bitmap_by_elapsed(GBitmapSequence *bitmap_sequence, GBitmap *bitmap, uint32_t elapsed_ms) { if (!bitmap_sequence) { return false; } // Disabled if play count is 0 and not the very first frame if (bitmap_sequence->play_count == 0 && bitmap_sequence->current_frame != 0) { return false; } // If animation has started and specified time is in the past if (bitmap_sequence->current_frame_delay_ms != 0 && elapsed_ms <= bitmap_sequence->elapsed_ms) { APP_LOG(APP_LOG_LEVEL_WARNING, APNG_ELAPSED_WARNING); return false; } bool retval = false; bool frame_updated = true; while (frame_updated && ((elapsed_ms > bitmap_sequence->elapsed_ms) || (bitmap_sequence->current_frame_delay_ms == 0))) { frame_updated = gbitmap_sequence_update_bitmap_next_frame(bitmap_sequence, bitmap, NULL); // If frame is updated at least once, return true if (frame_updated) { retval = true; } } return retval; } // Helper functions int32_t gbitmap_sequence_get_current_frame_idx(GBitmapSequence *bitmap_sequence) { if (bitmap_sequence) { return bitmap_sequence->current_frame; } return -1; } uint32_t gbitmap_sequence_get_current_frame_delay_ms(GBitmapSequence *bitmap_sequence) { if (bitmap_sequence) { return bitmap_sequence->current_frame_delay_ms; } return 0; } uint32_t gbitmap_sequence_get_total_num_frames(GBitmapSequence *bitmap_sequence) { if (bitmap_sequence) { return bitmap_sequence->total_frames; } return 0; } uint32_t gbitmap_sequence_get_play_count(GBitmapSequence *bitmap_sequence) { if (bitmap_sequence) { return bitmap_sequence->play_count; } return 0; } void gbitmap_sequence_set_play_count(GBitmapSequence *bitmap_sequence, uint32_t play_count) { // Loop count is not allowed to be set to 0 if (bitmap_sequence && play_count) { bitmap_sequence->play_count = play_count; } } GSize gbitmap_sequence_get_bitmap_size(GBitmapSequence *bitmap_sequence) { GSize size = (GSize){0, 0}; if (bitmap_sequence) <|fim_suffix|> return size; } uint32_t gbitmap_sequence_get_total_duration(GBitmapSequence *bitmap_sequence) { if (bitmap_sequence) { return bitmap_sequence->total_duration_ms; } return 0; } <|fim_middle|>{ size = bitmap_sequence->bitmap_size; }<|endoftext|>
masked_node
call_expression
tests/fw/applib/test_app_glance.c
nce read back with the expected glance below AppGlance expected_glance = (AppGlance) { .num_slices = 2, .slices = { { .expiration_time = rtc_get_time() + 10, .type = AppGlanceSliceType_IconAndSubtitle, .icon_and_subtitle.icon_resource_id = TIMELINE_RESOURCE_HOTEL_RESERVATION, .icon_and_subtitle.template_string = "Test subtitle", }, { .expiration_time = rtc_get_time() + 20, .type = AppGlanceSliceType_IconAndSubtitle, .icon_and_subtitle.icon_resource_id = APP_GLANCE_SLICE_DEFAULT_ICON, } }, }; cl_assert_equal_m(&glance, &expected_glance, sizeof(AppGlance)); } void prv_reload_with_validation_cb(AppGlanceReloadSession *session, size_t limit, void *context) { s_test_state.reload_callback_was_called = true; // Check that the context here is the context we passed to `app_glance_reload()` cl_assert_equal_p(context, s_test_state.context); // Check that the limit passed in matches the max slices per glance cl_assert_equal_i(limit, APP_GLANCE_DB_MAX_SLICES_PER_GLANCE); unsigned int num_slices_added = 0; AppGlanceSlice slice = {}; // Check that using a bogus session variable fails AppGlanceReloadSession bogus_session; cl_assert(app_glance_add_slice(&bogus_session, slice) & APP_GLANCE_RESULT_INVALID_SESSION); // Check that adding a slice with APP_GLANCE_SLICE_DEFAULT_ICON as the icon succeeds slice = (AppGlanceSlice) { .expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION, .layout.icon = APP_GLANCE_SLICE_DEFAULT_ICON, .layout.subtitle_template_string = "Test subtitle {time_until(500)|format('%uS')}", }; cl_assert_equal_i(app_glance_add_slice(session, slice), APP_GLANCE_RESULT_SUCCESS); num_slices_added++; // Check that adding a slice with a NULL subtitle succeeds s_test_state.resource_is_valid = true; slice = (AppGlanceSlice) { .expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION, .layout.icon = TIMELINE_RESOURCE_BIRTHDAY_EVENT, .layout.subtitle_template_string = NULL, }; cl_assert_equal_i(app_glance_add_slice(session, slice), APP_GLANCE_RESULT_SUCCESS); num_slices_added++; // Check that adding a slice with an invalid icon fails s_test_state.resource_is_valid = false; slice = (AppGlanceSlice) { .expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION, .layout.icon = RESOURCE_ID_SETTINGS_ICON_AIRPLANE, .layout.subtitle_template_string = "Test subtitle", }; cl_assert(app_glance_add_slice(session, slice) & APP_GLANCE_RESULT_INVALID_ICON); // Check that adding a slice with a subtitle that's too long fails const char *really_long_subtitle = "This is a really really really really really really really " "really really really really really really really really " "really really really really really really really really " "really really really really really really really really " "really long subtitle."; slice = (AppGlanceSlice) { .expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION, .layout.icon = APP_GLANCE_SLICE_DEFAULT_ICON, .layout.subtitle_template_string = really_long_subtitle, }; cl_assert(app_glance_add_slice(session, slice) & APP_GLANCE_RESULT_TEMPLATE_STRING_TOO_LONG); // Check that adding a slice with a bad template string fails const char *invalid_template_subtitle = "How much time? {time_until(500)|format('%uS',)}"; slice = (AppGlanceSlice) { .expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION, .layout.icon = APP_GLANCE_SLICE_DEFAULT_ICON, .layout.subtitle_template_string = invalid_template_subtitle, }; cl_assert(app_glance_add_slice(session, slice) & APP_GLANCE_RESULT_INVALID_TEMPLATE_STRING); // Check that adding a slice that expires in the past fails slice = (AppGlanceSlice) { .expiration_time = rtc_get_time() - 10, .layout.icon = APP_GLANCE_SLICE_DEFAULT_ICON, .layout.subtitle_template_string = "Test subtitle", }; cl_assert(
& APP_GLANCE_RESULT_EXPIRES_IN_THE_PAST); // At this point we've actually filled up the glance to the capacity cl_assert_equal_i(num_slices_added, limit); // So adding one more slice to the glance should fail s_test_state.resource_is_valid = true; slice = (AppGlanceSlice) { .expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION, .layout.subtitle_template_string = NULL, }; cl_assert(app_glance_add_slice(session, slice) & APP_GLANCE_RESULT_SLICE_CAPACITY_EXCEEDED); // Check that we can get reports of multiple kinds of failures at the same time s_test_state.resource_is_valid = false; slice = (AppGlanceSlice) { .expiration_time = rtc_get_time() - 10, .layout.icon = RESOURCE_ID_SETTINGS_ICON_AIRPLANE, .layout.subtitle_template_string = really_long_subtitle, }; const AppGlanceResult result = app_glance_add_slice(session, slice); cl_assert(result & APP_GLANCE_RESULT_EXPIRES_IN_THE_PAST); cl_assert(result & APP_GLANCE_RESULT_SLICE_CAPACITY_EXCEEDED); cl_assert(result & APP_GLANCE_RESULT_INVALID_ICON); cl_assert(result & APP_GLANCE_RESULT_TEMPLATE_STRING_TOO_LONG); } void test_app_glance__reload_with_validation_callback(void) { app_glance_reload(prv_reload_with_validation_cb, s_test_state.context); cl_assert_equal_b(s_test_state.reload_callback_was_called, true); } static void prv_glance_clear_test(AppGlanceReloadCallback reload_cb) { // Insert some slices for the glance const AppGlance glance = (AppGlance) { .num_slices = 2, .slices = { { .expiration_time = 1464734504, // (Tue, 31 May 2016 22:41:44 GMT) .type = AppGlanceSliceType_IconAndSubtitle, .icon_and_subtitle = { .template_string = "Test subtitle 2", }, }, { .expiration_time = 1464734484, // (Tue, 31 May 2016 22:41:24 GMT) .type = AppGlanceSliceType_IconAndSubtitle, .icon_and_subtitle = { .template_string = "Test subtitle 1", }, }, }, }; cl_assert_equal_i(app_glance_db_insert_glance(&APP_GLANCE_TEST_UUID, &glance), S_SUCCESS); // Request the current slice for this glance; this should match the earliest-expiring slice in // the glance we just inserted above AppGlanceSliceInternal slice_out; cl_assert_equal_b(app_glance_service_get_current_slice(&APP_GLANCE_TEST_UUID, &slice_out), true); cl_assert_equal_m(&slice_out, &glance.slices[1], sizeof(slice_out)); // Let some time "pass" so that the creation time of this next reload doesn't get ignored fake_rtc_increment_time(10); // Reload the glance using the provided callback; this should empty the slices in the glance app_glance_reload(reload_cb, NULL); // Read the glance back and check that it doesn't have any slices anymore AppGlance glance_read = {}; cl_assert_equal_i(app_glance_db_read_glance(&APP_GLANCE_TEST_UUID, &glance_read), S_SUCCESS); cl_assert_equal_i(glance_read.num_slices, 0); for (unsigned int i = 0; i < sizeof(glance_read.slices); i++) { const uint8_t byte = ((uint8_t *)glance_read.slices)[i]; cl_assert_equal_i(byte, 0); } // Request the current slice for this glance again; this should return false since there aren't // any slices in the glance anymore cl_assert_equal_b(app_glance_service_get_current_slice(&APP_GLANCE_TEST_UUID, &slice_out), false); } void test_app_glance__reload_with_null_callback_empties_slices(void) { prv_glance_clear_test(NULL); } static void prv_reload_with_no_slices_added_cb(AppGlanceReloadSession *session, size_t limit, void *context) { // We don't add any slices in this callback on purpose return; } void test_app_glance__reload_with_no_slices_added_empties_slices(void) { prv_glance_clear_test(prv_reload_with_no_slices_added_cb); }
app_glance_add_slice(session, slice)
<|repo_name|>pebble <|file_sep|>tests/fw/applib/test_app_glance.c <|fim_prefix|>nce read back with the expected glance below AppGlance expected_glance = (AppGlance) { .num_slices = 2, .slices = { { .expiration_time = rtc_get_time() + 10, .type = AppGlanceSliceType_IconAndSubtitle, .icon_and_subtitle.icon_resource_id = TIMELINE_RESOURCE_HOTEL_RESERVATION, .icon_and_subtitle.template_string = "Test subtitle", }, { .expiration_time = rtc_get_time() + 20, .type = AppGlanceSliceType_IconAndSubtitle, .icon_and_subtitle.icon_resource_id = APP_GLANCE_SLICE_DEFAULT_ICON, } }, }; cl_assert_equal_m(&glance, &expected_glance, sizeof(AppGlance)); } void prv_reload_with_validation_cb(AppGlanceReloadSession *session, size_t limit, void *context) { s_test_state.reload_callback_was_called = true; // Check that the context here is the context we passed to `app_glance_reload()` cl_assert_equal_p(context, s_test_state.context); // Check that the limit passed in matches the max slices per glance cl_assert_equal_i(limit, APP_GLANCE_DB_MAX_SLICES_PER_GLANCE); unsigned int num_slices_added = 0; AppGlanceSlice slice = {}; // Check that using a bogus session variable fails AppGlanceReloadSession bogus_session; cl_assert(app_glance_add_slice(&bogus_session, slice) & APP_GLANCE_RESULT_INVALID_SESSION); // Check that adding a slice with APP_GLANCE_SLICE_DEFAULT_ICON as the icon succeeds slice = (AppGlanceSlice) { .expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION, .layout.icon = APP_GLANCE_SLICE_DEFAULT_ICON, .layout.subtitle_template_string = "Test subtitle {time_until(500)|format('%uS')}", }; cl_assert_equal_i(app_glance_add_slice(session, slice), APP_GLANCE_RESULT_SUCCESS); num_slices_added++; // Check that adding a slice with a NULL subtitle succeeds s_test_state.resource_is_valid = true; slice = (AppGlanceSlice) { .expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION, .layout.icon = TIMELINE_RESOURCE_BIRTHDAY_EVENT, .layout.subtitle_template_string = NULL, }; cl_assert_equal_i(app_glance_add_slice(session, slice), APP_GLANCE_RESULT_SUCCESS); num_slices_added++; // Check that adding a slice with an invalid icon fails s_test_state.resource_is_valid = false; slice = (AppGlanceSlice) { .expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION, .layout.icon = RESOURCE_ID_SETTINGS_ICON_AIRPLANE, .layout.subtitle_template_string = "Test subtitle", }; cl_assert(app_glance_add_slice(session, slice) & APP_GLANCE_RESULT_INVALID_ICON); // Check that adding a slice with a subtitle that's too long fails const char *really_long_subtitle = "This is a really really really really really really really " "really really really really really really really really " "really really really really really really really really " "really really really really really really really really " "really long subtitle."; slice = (AppGlanceSlice) { .expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION, .layout.icon = APP_GLANCE_SLICE_DEFAULT_ICON, .layout.subtitle_template_string = really_long_subtitle, }; cl_assert(app_glance_add_slice(session, slice) & APP_GLANCE_RESULT_TEMPLATE_STRING_TOO_LONG); // Check that adding a slice with a bad template string fails const char *invalid_template_subtitle = "How much time? {time_until(500)|format('%uS',)}"; slice = (AppGlanceSlice) { .expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION, .layout.icon = APP_GLANCE_SLICE_DEFAULT_ICON, .layout.subtitle_template_string = invalid_template_subtitle, }; cl_assert(app_glance_add_slice(session, slice) & APP_GLANCE_RESULT_INVALID_TEMPLATE_STRING); // Check that adding a slice that expires in the past fails slice = (AppGlanceSlice) { .expiration_time = rtc_get_time() - 10, .layout.icon = APP_GLANCE_SLICE_DEFAULT_ICON, .layout.subtitle_template_string = "Test subtitle", }; cl_assert(<|fim_suffix|> & APP_GLANCE_RESULT_EXPIRES_IN_THE_PAST); // At this point we've actually filled up the glance to the capacity cl_assert_equal_i(num_slices_added, limit); // So adding one more slice to the glance should fail s_test_state.resource_is_valid = true; slice = (AppGlanceSlice) { .expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION, .layout.subtitle_template_string = NULL, }; cl_assert(app_glance_add_slice(session, slice) & APP_GLANCE_RESULT_SLICE_CAPACITY_EXCEEDED); // Check that we can get reports of multiple kinds of failures at the same time s_test_state.resource_is_valid = false; slice = (AppGlanceSlice) { .expiration_time = rtc_get_time() - 10, .layout.icon = RESOURCE_ID_SETTINGS_ICON_AIRPLANE, .layout.subtitle_template_string = really_long_subtitle, }; const AppGlanceResult result = app_glance_add_slice(session, slice); cl_assert(result & APP_GLANCE_RESULT_EXPIRES_IN_THE_PAST); cl_assert(result & APP_GLANCE_RESULT_SLICE_CAPACITY_EXCEEDED); cl_assert(result & APP_GLANCE_RESULT_INVALID_ICON); cl_assert(result & APP_GLANCE_RESULT_TEMPLATE_STRING_TOO_LONG); } void test_app_glance__reload_with_validation_callback(void) { app_glance_reload(prv_reload_with_validation_cb, s_test_state.context); cl_assert_equal_b(s_test_state.reload_callback_was_called, true); } static void prv_glance_clear_test(AppGlanceReloadCallback reload_cb) { // Insert some slices for the glance const AppGlance glance = (AppGlance) { .num_slices = 2, .slices = { { .expiration_time = 1464734504, // (Tue, 31 May 2016 22:41:44 GMT) .type = AppGlanceSliceType_IconAndSubtitle, .icon_and_subtitle = { .template_string = "Test subtitle 2", }, }, { .expiration_time = 1464734484, // (Tue, 31 May 2016 22:41:24 GMT) .type = AppGlanceSliceType_IconAndSubtitle, .icon_and_subtitle = { .template_string = "Test subtitle 1", }, }, }, }; cl_assert_equal_i(app_glance_db_insert_glance(&APP_GLANCE_TEST_UUID, &glance), S_SUCCESS); // Request the current slice for this glance; this should match the earliest-expiring slice in // the glance we just inserted above AppGlanceSliceInternal slice_out; cl_assert_equal_b(app_glance_service_get_current_slice(&APP_GLANCE_TEST_UUID, &slice_out), true); cl_assert_equal_m(&slice_out, &glance.slices[1], sizeof(slice_out)); // Let some time "pass" so that the creation time of this next reload doesn't get ignored fake_rtc_increment_time(10); // Reload the glance using the provided callback; this should empty the slices in the glance app_glance_reload(reload_cb, NULL); // Read the glance back and check that it doesn't have any slices anymore AppGlance glance_read = {}; cl_assert_equal_i(app_glance_db_read_glance(&APP_GLANCE_TEST_UUID, &glance_read), S_SUCCESS); cl_assert_equal_i(glance_read.num_slices, 0); for (unsigned int i = 0; i < sizeof(glance_read.slices); i++) { const uint8_t byte = ((uint8_t *)glance_read.slices)[i]; cl_assert_equal_i(byte, 0); } // Request the current slice for this glance again; this should return false since there aren't // any slices in the glance anymore cl_assert_equal_b(app_glance_service_get_current_slice(&APP_GLANCE_TEST_UUID, &slice_out), false); } void test_app_glance__reload_with_null_callback_empties_slices(void) { prv_glance_clear_test(NULL); } static void prv_reload_with_no_slices_added_cb(AppGlanceReloadSession *session, size_t limit, void *context) { // We don't add any slices in this callback on purpose return; } void test_app_glance__reload_with_no_slices_added_empties_slices(void) { prv_glance_clear_test(prv_reload_with_no_slices_added_cb); } <|fim_middle|>app_glance_add_slice(session, slice)<|endoftext|>
prefix_only
argument_list
tests/fw/applib/bluetooth/test_ble_ad_parse.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "applib/bluetooth/ble_ad_parse.h" #include "system/hexdump.h" #include "clar.h" #include <btutil/bt_uuid.h> // Stubs /////////////////////////////////////////////////////////// #include "stubs_ble_syscalls.h" #include "stubs_ble_syscalls.h" #include "stubs_logging.h" #include "stubs_passert.h" #include "stubs_pbl_malloc.h" #include "stubs_pebble_tasks.h" #include "stubs_print.h" #include "stubs_prompt.h" #include "stubs_rand_ptr.h" #include "stubs_serial.h" // The test data and descriptions in this file are captured using the FrontLine // Bluetooth sniffer. static const size_t s_buffer_size = sizeof(BLEAdData) + (2 * GAP_LE_AD_REPORT_DATA_MAX_LENGTH); static uint8_t s_buffer[s_buffer_size]; static BLEAdData * const s_ad_data = (BLEAdData *)s_buffer; static void set_ad_data(uint8_t *data, size_t length) { memcpy(s_ad_data->data, data, length); s_ad_data->ad_data_length = length; } void test_ble_ad_parse__initialize(void) { memset
(s_ad_data, 0, sizeof(s_buffer_size))
<|repo_name|>pebble <|file_sep|>tests/fw/applib/bluetooth/test_ble_ad_parse.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "applib/bluetooth/ble_ad_parse.h" #include "system/hexdump.h" #include "clar.h" #include <btutil/bt_uuid.h> // Stubs /////////////////////////////////////////////////////////// #include "stubs_ble_syscalls.h" #include "stubs_ble_syscalls.h" #include "stubs_logging.h" #include "stubs_passert.h" #include "stubs_pbl_malloc.h" #include "stubs_pebble_tasks.h" #include "stubs_print.h" #include "stubs_prompt.h" #include "stubs_rand_ptr.h" #include "stubs_serial.h" // The test data and descriptions in this file are captured using the FrontLine // Bluetooth sniffer. static const size_t s_buffer_size = sizeof(BLEAdData) + (2 * GAP_LE_AD_REPORT_DATA_MAX_LENGTH); static uint8_t s_buffer[s_buffer_size]; static BLEAdData * const s_ad_data = (BLEAdData *)s_buffer; static void set_ad_data(uint8_t *data, size_t length) { memcpy(s_ad_data->data, data, length); s_ad_data->ad_data_length = length; } void test_ble_ad_parse__initialize(void) { memset<|fim_suffix|><|fim_middle|>(s_ad_data, 0, sizeof(s_buffer_size))<|endoftext|>
masked_node
argument_list
tests/fw/ui/recognizer/test_recognizer.c
rt_passert(recognizer_transition_state(r, RecognizerState_Started)); event_type = -1; recognizer_transition_state(r, RecognizerState_Updated); cl_assert_equal_i(event_type, RecognizerEvent_Updated); cl_assert_equal_i(r->state, RecognizerState_Updated); cl_assert(!s_manager_state_change); recognizer_transition_state(r, RecognizerState_Completed); cl_assert_equal_i(event_type, RecognizerEvent_Completed); cl_assert_equal_i(r->state, RecognizerState_Completed); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Failed)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Possible)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Started)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Updated)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Cancelled)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Completed)); r->state = RecognizerState_Updated; recognizer_transition_state(r, RecognizerState_Cancelled); cl_assert_equal_i(event_type, RecognizerEvent_Cancelled); cl_assert_equal_i(r->state, RecognizerState_Cancelled); cl_assert(!s_manager_state_change); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Failed)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Possible)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Started)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Updated)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Cancelled)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Completed)); r->state = RecognizerState_Started; event_type = -1; recognizer_transition_state(r, RecognizerState_Cancelled); cl_assert_equal_i(event_type, RecognizerEvent_Cancelled); cl_assert_equal_i(r->state, RecognizerState_Cancelled); cl_assert(!s_manager_state_change); r->state = RecognizerState_Started; recognizer_transition_state(r, RecognizerState_Completed); cl_assert_equal_i(event_type, RecognizerEvent_Completed); cl_assert_equal_i(r->state, RecognizerState_Completed); cl_assert(!s_manager_state_change); r->state = RecognizerState_Possible; recognizer_transition_state(r, RecognizerState_Completed); cl_assert_equal_i(r->state, RecognizerState_Completed); cl_assert(!s_manager_state_change); } void test_recognizer__set_failed(void) { bool failed = false; s_test_impl_data.failed = &failed; NEW_RECOGNIZER(r) = test_recognizer_create(&s_test_impl_data, NULL); recognizer_set_failed(r); cl_assert_equal_i(r->state, RecognizerState_Failed); cl_assert(failed); // Failed -> Failed invalid transition cl_assert_passert(recognizer_set_failed(r)); // (!Possible) -> Failed invalid transition r->state = RecognizerState_Started; cl_assert_passert(recognizer_set_failed(r)); r->state = RecognizerState_Completed; cl_assert_passert(recognizer_set_failed(r)); } static void prv_sub_destroy(const Recognizer *r) { bool *destroyed = recognizer_get_user_data(r); *destroyed = true; } void test_recognizer__destroy(void) { bool impl_destroyed = false; s_test_impl_data.destroyed = &impl_destroyed; bool sub_destroyed = false; Recognizer *r = test_recognizer_create(&s_test_impl_data, &sub_destroyed); test_recognizer_enable_on_destroy(); recognizer_set_on_destroy(r, prv_sub_destroy); // can't destroy a recognizer if it is owned r->is_owned = true; recognizer_destroy(r); cl_assert_equal_b(impl_destroyed, false); cl_assert_equal_b(sub_destroyed, false); r->is_owned = false; recognizer_destroy(r); cl_assert_equal_b(impl_destroyed, true); cl_assert_equal_b(sub_destroyed, true); } void test_recognizer__reset(void) { bool reset = false; bool cancelled = false; s_test_impl_data.reset = &reset; s_test_impl_data.cancelled = &cancelled; NEW_RECOGNIZER(r) = test_recognizer_create(&s_test_impl_data, NULL); recognizer_reset(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b
; cl_assert_equal_b(cancelled, false); reset = false; r->state = RecognizerState_Failed; recognizer_reset(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b(reset, true); cl_assert_equal_b(cancelled, false); reset = false; r->state = RecognizerState_Cancelled; recognizer_reset(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b(reset, true); cl_assert_equal_b(cancelled, false); reset = false; r->state = RecognizerState_Completed; recognizer_reset(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b(reset, true); cl_assert_equal_b(cancelled, false); reset = false; r->state = RecognizerState_Started; recognizer_reset(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b(reset, true); cl_assert_equal_b(cancelled, true); reset = false; cancelled = false; r->state = RecognizerState_Updated; recognizer_reset(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b(reset, true); cl_assert_equal_b(cancelled, true); } void test_recognizer__cancel(void) { bool cancelled = false; s_test_impl_data.cancelled = &cancelled; RecognizerEvent rec_event = -1; NEW_RECOGNIZER(r) = test_recognizer_create(&s_test_impl_data, &rec_event); recognizer_cancel(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b(cancelled, false); cl_assert_equal_i(rec_event, -1); r->state = RecognizerState_Failed; recognizer_cancel(r); cl_assert_equal_i(r->state, RecognizerState_Failed); cl_assert_equal_b(cancelled, false); cl_assert_equal_i(rec_event, -1); r->state = RecognizerState_Cancelled; recognizer_cancel(r); cl_assert_equal_i(r->state, RecognizerState_Cancelled); cl_assert_equal_b(cancelled, false); cl_assert_equal_i(rec_event, -1); r->state = RecognizerState_Completed; recognizer_cancel(r); cl_assert_equal_i(r->state, RecognizerState_Completed); cl_assert_equal_b(cancelled, false); cl_assert_equal_i(rec_event, -1); r->state = RecognizerState_Started; recognizer_cancel(r); cl_assert_equal_i(r->state, RecognizerState_Cancelled); cl_assert_equal_b(cancelled, true); cl_assert_equal_i(rec_event, RecognizerEvent_Cancelled); cancelled = false; r->state = RecognizerState_Updated; rec_event = -1; recognizer_cancel(r); cl_assert_equal_i(r->state, RecognizerState_Cancelled); cl_assert_equal_b(cancelled, true); cl_assert_equal_i(rec_event, RecognizerEvent_Cancelled); } void test_recognizer__handle_touch_events(void) { RecognizerEvent rec_event = -1; TouchEvent last_touch_event = { .type = TouchEvent_Liftoff }; RecognizerState new_state; bool updated = false; s_test_impl_data.last_touch_event = &last_touch_event; s_test_impl_data.new_state = &new_state; s_test_impl_data.updated = &updated; NEW_RECOGNIZER(r) = test_recognizer_create(&s_test_impl_data, &rec_event); new_state = RecognizerState_Possible; recognizer_handle_touch_event(r, &(TouchEvent) { .type = TouchEvent_Touchdown }); cl_assert_equal_i(last_touch_event.type, TouchEvent_Touchdown); cl_assert_equal_b(updated, false); new_state = RecognizerState_Completed; recognizer_handle_touch_event(r, &(TouchEvent) { .type = TouchEvent_Liftoff }); cl_assert_equal_i(last_touch_event.type, TouchEvent_Liftoff); cl_assert_equal_b(updated, true); cl_assert_equal_i(rec_event, RecognizerEvent_Completed); r->state = RecognizerState_Possible; updated = false; new_state = RecognizerState_Started; recognizer_handle_touch_event(r, &(TouchEvent) { .type = TouchEvent_Touchdown }); cl_assert_equal_i(last_touch_event.type, TouchEvent_Touchdown); cl_assert_equal_b(updated, true); cl_assert_equal_i(rec_event, RecognizerEvent_Started); updated = false; new_state = RecognizerState_Updated; recognizer_handle_touch_event(r, &(TouchEvent) { .type = TouchEvent_PositionUpdate }); cl_assert_equal_i(last_touch_event.type, TouchEvent_PositionUpdate); cl_assert_equal_b(updated, true); cl_assert_eq
(reset, true)
<|repo_name|>pebble <|file_sep|>tests/fw/ui/recognizer/test_recognizer.c <|fim_prefix|>rt_passert(recognizer_transition_state(r, RecognizerState_Started)); event_type = -1; recognizer_transition_state(r, RecognizerState_Updated); cl_assert_equal_i(event_type, RecognizerEvent_Updated); cl_assert_equal_i(r->state, RecognizerState_Updated); cl_assert(!s_manager_state_change); recognizer_transition_state(r, RecognizerState_Completed); cl_assert_equal_i(event_type, RecognizerEvent_Completed); cl_assert_equal_i(r->state, RecognizerState_Completed); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Failed)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Possible)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Started)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Updated)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Cancelled)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Completed)); r->state = RecognizerState_Updated; recognizer_transition_state(r, RecognizerState_Cancelled); cl_assert_equal_i(event_type, RecognizerEvent_Cancelled); cl_assert_equal_i(r->state, RecognizerState_Cancelled); cl_assert(!s_manager_state_change); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Failed)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Possible)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Started)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Updated)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Cancelled)); cl_assert_passert(recognizer_transition_state(r, RecognizerState_Completed)); r->state = RecognizerState_Started; event_type = -1; recognizer_transition_state(r, RecognizerState_Cancelled); cl_assert_equal_i(event_type, RecognizerEvent_Cancelled); cl_assert_equal_i(r->state, RecognizerState_Cancelled); cl_assert(!s_manager_state_change); r->state = RecognizerState_Started; recognizer_transition_state(r, RecognizerState_Completed); cl_assert_equal_i(event_type, RecognizerEvent_Completed); cl_assert_equal_i(r->state, RecognizerState_Completed); cl_assert(!s_manager_state_change); r->state = RecognizerState_Possible; recognizer_transition_state(r, RecognizerState_Completed); cl_assert_equal_i(r->state, RecognizerState_Completed); cl_assert(!s_manager_state_change); } void test_recognizer__set_failed(void) { bool failed = false; s_test_impl_data.failed = &failed; NEW_RECOGNIZER(r) = test_recognizer_create(&s_test_impl_data, NULL); recognizer_set_failed(r); cl_assert_equal_i(r->state, RecognizerState_Failed); cl_assert(failed); // Failed -> Failed invalid transition cl_assert_passert(recognizer_set_failed(r)); // (!Possible) -> Failed invalid transition r->state = RecognizerState_Started; cl_assert_passert(recognizer_set_failed(r)); r->state = RecognizerState_Completed; cl_assert_passert(recognizer_set_failed(r)); } static void prv_sub_destroy(const Recognizer *r) { bool *destroyed = recognizer_get_user_data(r); *destroyed = true; } void test_recognizer__destroy(void) { bool impl_destroyed = false; s_test_impl_data.destroyed = &impl_destroyed; bool sub_destroyed = false; Recognizer *r = test_recognizer_create(&s_test_impl_data, &sub_destroyed); test_recognizer_enable_on_destroy(); recognizer_set_on_destroy(r, prv_sub_destroy); // can't destroy a recognizer if it is owned r->is_owned = true; recognizer_destroy(r); cl_assert_equal_b(impl_destroyed, false); cl_assert_equal_b(sub_destroyed, false); r->is_owned = false; recognizer_destroy(r); cl_assert_equal_b(impl_destroyed, true); cl_assert_equal_b(sub_destroyed, true); } void test_recognizer__reset(void) { bool reset = false; bool cancelled = false; s_test_impl_data.reset = &reset; s_test_impl_data.cancelled = &cancelled; NEW_RECOGNIZER(r) = test_recognizer_create(&s_test_impl_data, NULL); recognizer_reset(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b<|fim_suffix|>; cl_assert_equal_b(cancelled, false); reset = false; r->state = RecognizerState_Failed; recognizer_reset(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b(reset, true); cl_assert_equal_b(cancelled, false); reset = false; r->state = RecognizerState_Cancelled; recognizer_reset(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b(reset, true); cl_assert_equal_b(cancelled, false); reset = false; r->state = RecognizerState_Completed; recognizer_reset(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b(reset, true); cl_assert_equal_b(cancelled, false); reset = false; r->state = RecognizerState_Started; recognizer_reset(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b(reset, true); cl_assert_equal_b(cancelled, true); reset = false; cancelled = false; r->state = RecognizerState_Updated; recognizer_reset(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b(reset, true); cl_assert_equal_b(cancelled, true); } void test_recognizer__cancel(void) { bool cancelled = false; s_test_impl_data.cancelled = &cancelled; RecognizerEvent rec_event = -1; NEW_RECOGNIZER(r) = test_recognizer_create(&s_test_impl_data, &rec_event); recognizer_cancel(r); cl_assert_equal_i(r->state, RecognizerState_Possible); cl_assert_equal_b(cancelled, false); cl_assert_equal_i(rec_event, -1); r->state = RecognizerState_Failed; recognizer_cancel(r); cl_assert_equal_i(r->state, RecognizerState_Failed); cl_assert_equal_b(cancelled, false); cl_assert_equal_i(rec_event, -1); r->state = RecognizerState_Cancelled; recognizer_cancel(r); cl_assert_equal_i(r->state, RecognizerState_Cancelled); cl_assert_equal_b(cancelled, false); cl_assert_equal_i(rec_event, -1); r->state = RecognizerState_Completed; recognizer_cancel(r); cl_assert_equal_i(r->state, RecognizerState_Completed); cl_assert_equal_b(cancelled, false); cl_assert_equal_i(rec_event, -1); r->state = RecognizerState_Started; recognizer_cancel(r); cl_assert_equal_i(r->state, RecognizerState_Cancelled); cl_assert_equal_b(cancelled, true); cl_assert_equal_i(rec_event, RecognizerEvent_Cancelled); cancelled = false; r->state = RecognizerState_Updated; rec_event = -1; recognizer_cancel(r); cl_assert_equal_i(r->state, RecognizerState_Cancelled); cl_assert_equal_b(cancelled, true); cl_assert_equal_i(rec_event, RecognizerEvent_Cancelled); } void test_recognizer__handle_touch_events(void) { RecognizerEvent rec_event = -1; TouchEvent last_touch_event = { .type = TouchEvent_Liftoff }; RecognizerState new_state; bool updated = false; s_test_impl_data.last_touch_event = &last_touch_event; s_test_impl_data.new_state = &new_state; s_test_impl_data.updated = &updated; NEW_RECOGNIZER(r) = test_recognizer_create(&s_test_impl_data, &rec_event); new_state = RecognizerState_Possible; recognizer_handle_touch_event(r, &(TouchEvent) { .type = TouchEvent_Touchdown }); cl_assert_equal_i(last_touch_event.type, TouchEvent_Touchdown); cl_assert_equal_b(updated, false); new_state = RecognizerState_Completed; recognizer_handle_touch_event(r, &(TouchEvent) { .type = TouchEvent_Liftoff }); cl_assert_equal_i(last_touch_event.type, TouchEvent_Liftoff); cl_assert_equal_b(updated, true); cl_assert_equal_i(rec_event, RecognizerEvent_Completed); r->state = RecognizerState_Possible; updated = false; new_state = RecognizerState_Started; recognizer_handle_touch_event(r, &(TouchEvent) { .type = TouchEvent_Touchdown }); cl_assert_equal_i(last_touch_event.type, TouchEvent_Touchdown); cl_assert_equal_b(updated, true); cl_assert_equal_i(rec_event, RecognizerEvent_Started); updated = false; new_state = RecognizerState_Updated; recognizer_handle_touch_event(r, &(TouchEvent) { .type = TouchEvent_PositionUpdate }); cl_assert_equal_i(last_touch_event.type, TouchEvent_PositionUpdate); cl_assert_equal_b(updated, true); cl_assert_eq<|fim_middle|>(reset, true)<|endoftext|>
masked_node
argument_list
src/fw/apps/system_apps/hrm_demo.c
ta->out_iter, AppMessageKey_HRMHardwareRevision, hrm_info.hw_revision); } #endif char serial_number_buffer[MFG_SERIAL_NUMBER_SIZE + 1]; mfg_info_get_serialnumber(serial_number_buffer, sizeof(serial_number_buffer)); dict_write_data(app_data->out_iter, AppMessageKey_SerialNumber, (uint8_t*) serial_number_buffer, sizeof(serial_number_buffer)); #if IS_BIGBOARD WatchInfoColor watch_color = WATCH_INFO_MODEL_UNKNOWN; #else WatchInfoColor watch_color = mfg_info_get_watch_color(); #endif // IS_BIGBOARD dict_write_uint32(app_data->out_iter, AppMessageKey_Model, watch_color); prv_send_msg(); } static void prv_handle_hrm_data(PebbleEvent *e, void *context) { AppData *app_data = app_state_get_user_data(); if (e->type == PEBBLE_HRM_EVENT) { PebbleHRMEvent *hrm = &e->hrm; // Save HRMEventBPM data and send when we get the current into. static uint8_t bpm = 0; static uint8_t bpm_quality = 0; static uint16_t led_current = 0; if (hrm->event_type == HRMEvent_BPM) { snprintf(app_data->bpm_string, sizeof(app_data->bpm_string), "%"PRIu8" BPM", hrm->bpm.bpm); text_layer_set_text(&app_data->quality_text_layer, prv_get_quality_string(hrm->bpm.quality)); layer_mark_dirty(&app_data->window.layer); bpm = hrm->bpm.bpm; bpm_quality = hrm->bpm.quality; } else if (hrm->event_type == HRMEvent_LEDCurrent) { led_current = hrm->led.current_ua; } else if (hrm->event_type == HRMEvent_Diagnostics) { if (!app_data->ready_to_send) { return; } AppMessageResult result = app_message_outbox_begin(&app_data->out_iter); PBL_ASSERTN(result == APP_MSG_OK); if (bpm) { dict_write_uint8(app_data->out_iter, AppMessageKey_HeartRate, bpm); dict_write_uint8(app_data->out_iter, AppMessageKey_Confidence, bpm_quality); } if (led_current) { dict_write_uint16(app_data->out_iter, AppMessageKey_Current, led_current); } if (hrm->debug->ppg_data.num_samples) { HRMPPGData *d = &hrm->debug->ppg_data; dict_write_data(app_data->out_iter, AppMessageKey_TIA, (uint8_t *)d->tia, d->num_samples * sizeof(d->tia[0])); dict_write_data(app_data->out_iter, AppMessageKey_PPG, (uint8_t *)d->ppg, d->num_samples * sizeof(d->ppg[0])); } if (hrm->debug->ppg_data.tia[hrm->debug->ppg_data.num_samples - 1] == 0) { PBL_LOG_COLOR(LOG_LEVEL_DEBUG, LOG_COLOR_CYAN, "last PPG TIA sample is 0!"); } if (hrm->debug->ppg_data.num_samples != 20) { PBL_LOG_COLOR(LOG_LEVEL_DEBUG, LOG_COLOR_CYAN, "Only got %"PRIu16" samples!", hrm->debug->ppg_data.num_samples); } if (hrm->debug->accel_data.num_samples) { HRMAccelData *d = &hrm->debug->accel_data; dict_write_data(app_data->out_iter, AppMessageKey_AccelData, (uint8_t *)d->data, d->num_samples * sizeof(d->data[0])); } PBL_LOG(LOG_LEVEL_DEBUG, "Sending message - bpm:%u quality:%u current:%u " "ppg_readings:%u accel_readings %"PRIu32, bpm, bpm_quality, led_current, hrm->debug->ppg_data.num_samples, hrm->debug->accel_data.num_samples); led_current = bpm = bpm_quality = 0; prv_send_msg(); } else if (hrm->event_type == HRMEvent_SubscriptionExpiring) { PBL_LOG(LOG_LEVEL_INFO, "Got subscription expiring event"); // Subscribe again if our subscription is expiring const uint32_t update_time_s = 1; app_data->session = sys_hrm_manager_app_subscribe(APP_ID_HRM_DEMO, update_time_s, SECONDS_PER_HOUR, HRMFeature_BPM); } } } static void prv_enable_hrm(void) { AppData *app_data = app_state_get_user_data(); app_data->hrm_event_info = (EventServiceInfo) { .type = PEBBLE_HRM_EVENT, .handler = prv_handle_hrm_data, }; event_service_client_subscribe
; // TODO: Let the mobile app control this? const uint32_t update_time_s = 1; app_data->session = sys_hrm_manager_app_subscribe( APP_ID_HRM_DEMO, update_time_s, SECONDS_PER_HOUR, HRMFeature_BPM | HRMFeature_LEDCurrent | HRMFeature_Diagnostics); } static void prv_disable_hrm(void) { AppData *app_data = app_state_get_user_data(); event_service_client_unsubscribe(&app_data->hrm_event_info); sys_hrm_manager_unsubscribe(app_data->session); } static void prv_handle_mobile_status_request(AppStatus status) { AppData *app_data = app_state_get_user_data(); if (status == AppStatus_Stopped) { text_layer_set_text(&app_data->bpm_text_layer, "Paused"); text_layer_set_text(&app_data->quality_text_layer, "Paused by mobile"); prv_disable_hrm(); } else { app_data->bpm_string[0] = '\0'; text_layer_set_text(&app_data->bpm_text_layer, app_data->bpm_string); text_layer_set_text(&app_data->quality_text_layer, "Loading..."); prv_enable_hrm(); } } static void prv_message_received_cb(DictionaryIterator *iterator, void *context) { Tuple *status_tuple = dict_find(iterator, AppMessageKey_Status); if (status_tuple) { prv_handle_mobile_status_request(status_tuple->value->uint8); } } static void prv_message_sent_cb(DictionaryIterator *iterator, void *context) { AppData *app_data = app_state_get_user_data(); app_data->ready_to_send = true; } static void prv_message_failed_cb(DictionaryIterator *iterator, AppMessageResult reason, void *context) { PBL_LOG(LOG_LEVEL_DEBUG, "Out message send failed - reason %i %s", reason, prv_translate_error(reason)); AppData *app_data = app_state_get_user_data(); app_data->ready_to_send = true; } static void prv_remote_notify_timer_cb(void *data) { prv_send_status_and_version(); } static void prv_init(void) { AppData *app_data = app_malloc_check(sizeof(*app_data)); *app_data = (AppData) { .session = (HRMSessionRef)app_data, // Use app data as session ref .ready_to_send = false, }; app_state_set_user_data(app_data); Window *window = &app_data->window; window_init(window, ""); window_set_fullscreen(window, true); GRect bounds = window->layer.bounds; bounds.origin.y += 40; TextLayer *bpm_tl = &app_data->bpm_text_layer; text_layer_init(bpm_tl, &bounds); text_layer_set_font(bpm_tl, fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD)); text_layer_set_text_alignment(bpm_tl, GTextAlignmentCenter); text_layer_set_text(bpm_tl, app_data->bpm_string); layer_add_child(&window->layer, &bpm_tl->layer); bounds.origin.y += 35; TextLayer *quality_tl = &app_data->quality_text_layer; text_layer_init(quality_tl, &bounds); text_layer_set_font(quality_tl, fonts_get_system_font(FONT_KEY_GOTHIC_18)); text_layer_set_text_alignment(quality_tl, GTextAlignmentCenter); text_layer_set_text(quality_tl, "Loading..."); layer_add_child(&window->layer, &quality_tl->layer); const uint32_t inbox_size = 64; const uint32_t outbox_size = 256; AppMessageResult result = app_message_open(inbox_size, outbox_size); if (result != APP_MSG_OK) { PBL_LOG(LOG_LEVEL_ERROR, "Unable to open app message! %i %s", result, prv_translate_error(result)); } else { PBL_LOG(LOG_LEVEL_DEBUG, "Successfully opened app message"); } if (!sys_hrm_manager_is_hrm_present()) { text_layer_set_text(quality_tl, "No HRM Present"); } else { text_layer_set_text(quality_tl, "Loading..."); prv_enable_hrm(); } app_message_register_inbox_received(prv_message_received_cb); app_message_register_outbox_sent(prv_message_sent_cb); app_message_register_outbox_failed(prv_message_failed_cb); app_timer_register(1000, prv_remote_notify_timer_cb, NULL); app_window_stack_push(window, true); } static void prv_deinit(void) { AppData *app_data = app_state_get_user_data(); sys_hrm_manager_unsubscribe(app_data->session); } static void prv_main(void) { prv_init(); app_event_loop(); prv_deinit(); } const PebbleProcessMd* hrm_demo_get_app_info(void)
(&app_data->hrm_event_info)
<|repo_name|>pebble <|file_sep|>src/fw/apps/system_apps/hrm_demo.c <|fim_prefix|>ta->out_iter, AppMessageKey_HRMHardwareRevision, hrm_info.hw_revision); } #endif char serial_number_buffer[MFG_SERIAL_NUMBER_SIZE + 1]; mfg_info_get_serialnumber(serial_number_buffer, sizeof(serial_number_buffer)); dict_write_data(app_data->out_iter, AppMessageKey_SerialNumber, (uint8_t*) serial_number_buffer, sizeof(serial_number_buffer)); #if IS_BIGBOARD WatchInfoColor watch_color = WATCH_INFO_MODEL_UNKNOWN; #else WatchInfoColor watch_color = mfg_info_get_watch_color(); #endif // IS_BIGBOARD dict_write_uint32(app_data->out_iter, AppMessageKey_Model, watch_color); prv_send_msg(); } static void prv_handle_hrm_data(PebbleEvent *e, void *context) { AppData *app_data = app_state_get_user_data(); if (e->type == PEBBLE_HRM_EVENT) { PebbleHRMEvent *hrm = &e->hrm; // Save HRMEventBPM data and send when we get the current into. static uint8_t bpm = 0; static uint8_t bpm_quality = 0; static uint16_t led_current = 0; if (hrm->event_type == HRMEvent_BPM) { snprintf(app_data->bpm_string, sizeof(app_data->bpm_string), "%"PRIu8" BPM", hrm->bpm.bpm); text_layer_set_text(&app_data->quality_text_layer, prv_get_quality_string(hrm->bpm.quality)); layer_mark_dirty(&app_data->window.layer); bpm = hrm->bpm.bpm; bpm_quality = hrm->bpm.quality; } else if (hrm->event_type == HRMEvent_LEDCurrent) { led_current = hrm->led.current_ua; } else if (hrm->event_type == HRMEvent_Diagnostics) { if (!app_data->ready_to_send) { return; } AppMessageResult result = app_message_outbox_begin(&app_data->out_iter); PBL_ASSERTN(result == APP_MSG_OK); if (bpm) { dict_write_uint8(app_data->out_iter, AppMessageKey_HeartRate, bpm); dict_write_uint8(app_data->out_iter, AppMessageKey_Confidence, bpm_quality); } if (led_current) { dict_write_uint16(app_data->out_iter, AppMessageKey_Current, led_current); } if (hrm->debug->ppg_data.num_samples) { HRMPPGData *d = &hrm->debug->ppg_data; dict_write_data(app_data->out_iter, AppMessageKey_TIA, (uint8_t *)d->tia, d->num_samples * sizeof(d->tia[0])); dict_write_data(app_data->out_iter, AppMessageKey_PPG, (uint8_t *)d->ppg, d->num_samples * sizeof(d->ppg[0])); } if (hrm->debug->ppg_data.tia[hrm->debug->ppg_data.num_samples - 1] == 0) { PBL_LOG_COLOR(LOG_LEVEL_DEBUG, LOG_COLOR_CYAN, "last PPG TIA sample is 0!"); } if (hrm->debug->ppg_data.num_samples != 20) { PBL_LOG_COLOR(LOG_LEVEL_DEBUG, LOG_COLOR_CYAN, "Only got %"PRIu16" samples!", hrm->debug->ppg_data.num_samples); } if (hrm->debug->accel_data.num_samples) { HRMAccelData *d = &hrm->debug->accel_data; dict_write_data(app_data->out_iter, AppMessageKey_AccelData, (uint8_t *)d->data, d->num_samples * sizeof(d->data[0])); } PBL_LOG(LOG_LEVEL_DEBUG, "Sending message - bpm:%u quality:%u current:%u " "ppg_readings:%u accel_readings %"PRIu32, bpm, bpm_quality, led_current, hrm->debug->ppg_data.num_samples, hrm->debug->accel_data.num_samples); led_current = bpm = bpm_quality = 0; prv_send_msg(); } else if (hrm->event_type == HRMEvent_SubscriptionExpiring) { PBL_LOG(LOG_LEVEL_INFO, "Got subscription expiring event"); // Subscribe again if our subscription is expiring const uint32_t update_time_s = 1; app_data->session = sys_hrm_manager_app_subscribe(APP_ID_HRM_DEMO, update_time_s, SECONDS_PER_HOUR, HRMFeature_BPM); } } } static void prv_enable_hrm(void) { AppData *app_data = app_state_get_user_data(); app_data->hrm_event_info = (EventServiceInfo) { .type = PEBBLE_HRM_EVENT, .handler = prv_handle_hrm_data, }; event_service_client_subscribe<|fim_suffix|>; // TODO: Let the mobile app control this? const uint32_t update_time_s = 1; app_data->session = sys_hrm_manager_app_subscribe( APP_ID_HRM_DEMO, update_time_s, SECONDS_PER_HOUR, HRMFeature_BPM | HRMFeature_LEDCurrent | HRMFeature_Diagnostics); } static void prv_disable_hrm(void) { AppData *app_data = app_state_get_user_data(); event_service_client_unsubscribe(&app_data->hrm_event_info); sys_hrm_manager_unsubscribe(app_data->session); } static void prv_handle_mobile_status_request(AppStatus status) { AppData *app_data = app_state_get_user_data(); if (status == AppStatus_Stopped) { text_layer_set_text(&app_data->bpm_text_layer, "Paused"); text_layer_set_text(&app_data->quality_text_layer, "Paused by mobile"); prv_disable_hrm(); } else { app_data->bpm_string[0] = '\0'; text_layer_set_text(&app_data->bpm_text_layer, app_data->bpm_string); text_layer_set_text(&app_data->quality_text_layer, "Loading..."); prv_enable_hrm(); } } static void prv_message_received_cb(DictionaryIterator *iterator, void *context) { Tuple *status_tuple = dict_find(iterator, AppMessageKey_Status); if (status_tuple) { prv_handle_mobile_status_request(status_tuple->value->uint8); } } static void prv_message_sent_cb(DictionaryIterator *iterator, void *context) { AppData *app_data = app_state_get_user_data(); app_data->ready_to_send = true; } static void prv_message_failed_cb(DictionaryIterator *iterator, AppMessageResult reason, void *context) { PBL_LOG(LOG_LEVEL_DEBUG, "Out message send failed - reason %i %s", reason, prv_translate_error(reason)); AppData *app_data = app_state_get_user_data(); app_data->ready_to_send = true; } static void prv_remote_notify_timer_cb(void *data) { prv_send_status_and_version(); } static void prv_init(void) { AppData *app_data = app_malloc_check(sizeof(*app_data)); *app_data = (AppData) { .session = (HRMSessionRef)app_data, // Use app data as session ref .ready_to_send = false, }; app_state_set_user_data(app_data); Window *window = &app_data->window; window_init(window, ""); window_set_fullscreen(window, true); GRect bounds = window->layer.bounds; bounds.origin.y += 40; TextLayer *bpm_tl = &app_data->bpm_text_layer; text_layer_init(bpm_tl, &bounds); text_layer_set_font(bpm_tl, fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD)); text_layer_set_text_alignment(bpm_tl, GTextAlignmentCenter); text_layer_set_text(bpm_tl, app_data->bpm_string); layer_add_child(&window->layer, &bpm_tl->layer); bounds.origin.y += 35; TextLayer *quality_tl = &app_data->quality_text_layer; text_layer_init(quality_tl, &bounds); text_layer_set_font(quality_tl, fonts_get_system_font(FONT_KEY_GOTHIC_18)); text_layer_set_text_alignment(quality_tl, GTextAlignmentCenter); text_layer_set_text(quality_tl, "Loading..."); layer_add_child(&window->layer, &quality_tl->layer); const uint32_t inbox_size = 64; const uint32_t outbox_size = 256; AppMessageResult result = app_message_open(inbox_size, outbox_size); if (result != APP_MSG_OK) { PBL_LOG(LOG_LEVEL_ERROR, "Unable to open app message! %i %s", result, prv_translate_error(result)); } else { PBL_LOG(LOG_LEVEL_DEBUG, "Successfully opened app message"); } if (!sys_hrm_manager_is_hrm_present()) { text_layer_set_text(quality_tl, "No HRM Present"); } else { text_layer_set_text(quality_tl, "Loading..."); prv_enable_hrm(); } app_message_register_inbox_received(prv_message_received_cb); app_message_register_outbox_sent(prv_message_sent_cb); app_message_register_outbox_failed(prv_message_failed_cb); app_timer_register(1000, prv_remote_notify_timer_cb, NULL); app_window_stack_push(window, true); } static void prv_deinit(void) { AppData *app_data = app_state_get_user_data(); sys_hrm_manager_unsubscribe(app_data->session); } static void prv_main(void) { prv_init(); app_event_loop(); prv_deinit(); } const PebbleProcessMd* hrm_demo_get_app_info(void) <|fim_middle|>(&app_data->hrm_event_info)<|endoftext|>
masked_node
if_statement
src/fw/services/normal/timeline/item.c
r->common = item->header; header->payload_length = payload_length; header->num_attributes = item->attr_list.num_attributes; header->num_actions = item->action_group.num_actions; } void timeline_item_deserialize_header(TimelineItem *item, const SerializedTimelineItemHeader *header) { PBL_ASSERTN(item != NULL); PBL_ASSERTN(header != NULL); item->header = header->common; item->attr_list.num_attributes = header->num_attributes; item->action_group.num_actions = header->num_actions; item->header.timestamp = timeline_item_get_tz_timestamp(&item->header); } time_t timeline_item_get_tz_timestamp(CommonTimelineItemHeader *hdr) { bool should_adjust = hdr->all_day || hdr->is_floating; time_t timestamp = hdr->timestamp; if (should_adjust) { timestamp = time_local_to_utc(timestamp); } return timestamp; } size_t timeline_item_serialize_payload(TimelineItem *item, uint8_t *buffer, size_t buffer_size) { PBL_ASSERTN(item != NULL); return attributes_actions_serialize_payload(&item->attr_list, &item->action_group, buffer, buffer_size); } bool timeline_item_deserialize_payload(TimelineItem *item, char *string_buffer, size_t string_buffer_size, const uint8_t *payload, size_t payload_size) { PBL_ASSERTN(item != NULL); PBL_ASSERTN(string_buffer != NULL); PBL_ASSERTN(payload != NULL); uint8_t *buf_end = (uint8_t *)string_buffer + string_buffer_size; return attributes_actions_deserialize(&item->attr_list, &item->action_group, (uint8_t*) string_buffer, buf_end, payload, payload_size); } void timeline_item_destroy(TimelineItem* item) { if (item != NULL) { timeline_item_free_allocated_buffer(item); task_free(item); } } void timeline_item_free_allocated_buffer(TimelineItem *item) { if (item->allocated_buffer != NULL) { task_free(item->allocated_buffer); item->allocated_buffer = NULL; } } bool timeline_item_verify_layout_serialized(const uint8_t *val, int val_len) { SerializedTimelineItemHeader *hdr = (SerializedTimelineItemHeader *)val; bool has_attribute[NumAttributeIds] = {0}; // verify that the serialized attributes are well-formed const uint8_t *cursor = val + sizeof(SerializedTimelineItemHeader); const uint8_t *val_end = val + val_len; if (!attribute_check_serialized_list(cursor, val_end, hdr->num_attributes, has_attribute)) { PBL_LOG(LOG_LEVEL_ERROR, "Could not deserialize attributes to verify"); return false; } // verify that the layout of the item has the attribute it requires LayoutId layout = hdr->common.layout; PBL_LOG(LOG_LEVEL_DEBUG, "Number of attributes: %d for layout: %d", hdr->num_attributes, layout); return layout_verify(has_attribute, layout); } bool timeline_item_action_is_dismiss(const TimelineItemAction *action) { return (action->type == TimelineItemActionTypeAncsNegative || action->type == TimelineItemActionTypeDismiss); } bool timeline_item_action_is_ancs(const TimelineItemAction *action) { return action->type == TimelineItemActionTypeAncsNegative || action->type == TimelineItemActionTypeAncsDelete || action->type == TimelineItemActionTypeAncsDial || action->type == TimelineItemActionTypeAncsPositive; } bool timeline_item_is_ancs_notif(const TimelineItem *item) { return item->header.ancs_notif; } // ------------------------------------------------------------------------------------------------ // Action finding functions typedef bool (*ActionCompareFunc)(const TimelineItemAction *action, void* data); static TimelineItemAction *prv_find_action(const TimelineItemActionGroup *action_group, ActionCompareFunc compare_func, void *data) { for (int i = 0; i < action_group->num_actions; i++) { TimelineItemAction *action = &action_group->actions[i];
} return NULL; } static TimelineItemAction *prv_item_find_action(const TimelineItem *item, ActionCompareFunc compare_func, void *data) { if (!prv_is_valid_item(item)) { return NULL; } return prv_find_action(&item->action_group, compare_func, data); } static bool prv_action_id_compare_func(const TimelineItemAction *action, void* data) { uint8_t *action_id = data; return (action->id == *action_id); } const TimelineItemAction *timeline_item_find_action_with_id(const TimelineItem *item, uint8_t action_id) { return prv_item_find_action(item, prv_action_id_compare_func, &action_id); } static bool prv_action_type_compare_func(const TimelineItemAction *action, void* data) { TimelineItemActionType *type = data; return (action->type == *type); } TimelineItemAction *timeline_item_find_action_by_type(const TimelineItem *item, TimelineItemActionType type) { return prv_item_find_action(item, prv_action_type_compare_func, &type); } static bool prv_action_dismiss_compare_func(const TimelineItemAction *action, void* data) { return timeline_item_action_is_dismiss(action); } TimelineItemAction *timeline_item_find_dismiss_action(const TimelineItem *item) { return prv_item_find_action(item, prv_action_dismiss_compare_func, NULL); } static bool prv_action_reply_compare_func(const TimelineItemAction *action, void* data) { return (action->type == TimelineItemActionTypeAncsResponse) || (action->type == TimelineItemActionTypeResponse); } TimelineItemAction *timeline_item_find_reply_action(const TimelineItem *item) { return prv_item_find_action(item, prv_action_reply_compare_func, NULL); } TimelineItemAction *timeline_item_action_group_find_reply_action( const TimelineItemActionGroup *action_group) { return prv_find_action(action_group, prv_action_reply_compare_func, NULL); }
if (compare_func(action, data)) { return action; }
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/timeline/item.c <|fim_prefix|>r->common = item->header; header->payload_length = payload_length; header->num_attributes = item->attr_list.num_attributes; header->num_actions = item->action_group.num_actions; } void timeline_item_deserialize_header(TimelineItem *item, const SerializedTimelineItemHeader *header) { PBL_ASSERTN(item != NULL); PBL_ASSERTN(header != NULL); item->header = header->common; item->attr_list.num_attributes = header->num_attributes; item->action_group.num_actions = header->num_actions; item->header.timestamp = timeline_item_get_tz_timestamp(&item->header); } time_t timeline_item_get_tz_timestamp(CommonTimelineItemHeader *hdr) { bool should_adjust = hdr->all_day || hdr->is_floating; time_t timestamp = hdr->timestamp; if (should_adjust) { timestamp = time_local_to_utc(timestamp); } return timestamp; } size_t timeline_item_serialize_payload(TimelineItem *item, uint8_t *buffer, size_t buffer_size) { PBL_ASSERTN(item != NULL); return attributes_actions_serialize_payload(&item->attr_list, &item->action_group, buffer, buffer_size); } bool timeline_item_deserialize_payload(TimelineItem *item, char *string_buffer, size_t string_buffer_size, const uint8_t *payload, size_t payload_size) { PBL_ASSERTN(item != NULL); PBL_ASSERTN(string_buffer != NULL); PBL_ASSERTN(payload != NULL); uint8_t *buf_end = (uint8_t *)string_buffer + string_buffer_size; return attributes_actions_deserialize(&item->attr_list, &item->action_group, (uint8_t*) string_buffer, buf_end, payload, payload_size); } void timeline_item_destroy(TimelineItem* item) { if (item != NULL) { timeline_item_free_allocated_buffer(item); task_free(item); } } void timeline_item_free_allocated_buffer(TimelineItem *item) { if (item->allocated_buffer != NULL) { task_free(item->allocated_buffer); item->allocated_buffer = NULL; } } bool timeline_item_verify_layout_serialized(const uint8_t *val, int val_len) { SerializedTimelineItemHeader *hdr = (SerializedTimelineItemHeader *)val; bool has_attribute[NumAttributeIds] = {0}; // verify that the serialized attributes are well-formed const uint8_t *cursor = val + sizeof(SerializedTimelineItemHeader); const uint8_t *val_end = val + val_len; if (!attribute_check_serialized_list(cursor, val_end, hdr->num_attributes, has_attribute)) { PBL_LOG(LOG_LEVEL_ERROR, "Could not deserialize attributes to verify"); return false; } // verify that the layout of the item has the attribute it requires LayoutId layout = hdr->common.layout; PBL_LOG(LOG_LEVEL_DEBUG, "Number of attributes: %d for layout: %d", hdr->num_attributes, layout); return layout_verify(has_attribute, layout); } bool timeline_item_action_is_dismiss(const TimelineItemAction *action) { return (action->type == TimelineItemActionTypeAncsNegative || action->type == TimelineItemActionTypeDismiss); } bool timeline_item_action_is_ancs(const TimelineItemAction *action) { return action->type == TimelineItemActionTypeAncsNegative || action->type == TimelineItemActionTypeAncsDelete || action->type == TimelineItemActionTypeAncsDial || action->type == TimelineItemActionTypeAncsPositive; } bool timeline_item_is_ancs_notif(const TimelineItem *item) { return item->header.ancs_notif; } // ------------------------------------------------------------------------------------------------ // Action finding functions typedef bool (*ActionCompareFunc)(const TimelineItemAction *action, void* data); static TimelineItemAction *prv_find_action(const TimelineItemActionGroup *action_group, ActionCompareFunc compare_func, void *data) { for (int i = 0; i < action_group->num_actions; i++) { TimelineItemAction *action = &action_group->actions[i]; <|fim_suffix|> } return NULL; } static TimelineItemAction *prv_item_find_action(const TimelineItem *item, ActionCompareFunc compare_func, void *data) { if (!prv_is_valid_item(item)) { return NULL; } return prv_find_action(&item->action_group, compare_func, data); } static bool prv_action_id_compare_func(const TimelineItemAction *action, void* data) { uint8_t *action_id = data; return (action->id == *action_id); } const TimelineItemAction *timeline_item_find_action_with_id(const TimelineItem *item, uint8_t action_id) { return prv_item_find_action(item, prv_action_id_compare_func, &action_id); } static bool prv_action_type_compare_func(const TimelineItemAction *action, void* data) { TimelineItemActionType *type = data; return (action->type == *type); } TimelineItemAction *timeline_item_find_action_by_type(const TimelineItem *item, TimelineItemActionType type) { return prv_item_find_action(item, prv_action_type_compare_func, &type); } static bool prv_action_dismiss_compare_func(const TimelineItemAction *action, void* data) { return timeline_item_action_is_dismiss(action); } TimelineItemAction *timeline_item_find_dismiss_action(const TimelineItem *item) { return prv_item_find_action(item, prv_action_dismiss_compare_func, NULL); } static bool prv_action_reply_compare_func(const TimelineItemAction *action, void* data) { return (action->type == TimelineItemActionTypeAncsResponse) || (action->type == TimelineItemActionTypeResponse); } TimelineItemAction *timeline_item_find_reply_action(const TimelineItem *item) { return prv_item_find_action(item, prv_action_reply_compare_func, NULL); } TimelineItemAction *timeline_item_action_group_find_reply_action( const TimelineItemActionGroup *action_group) { return prv_find_action(action_group, prv_action_reply_compare_func, NULL); } <|fim_middle|>if (compare_func(action, data)) { return action; }<|endoftext|>
masked_node
if_statement
src/apps/strftime_test/src/strftime_test.c
s expected r = strftime(buf, buf_size, "%a", &good_data); if (r == 0 || strncmp(buf, "Tue", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"a\": %s", buf); } r = strftime(buf, buf_size, "%A", &good_data); if (r == 0 || strncmp(buf, "Tuesday", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"A\": %s", buf); } r = strftime(buf, buf_size, "%b", &good_data); if (r == 0 || strncmp(buf, "May", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"b\": %s", buf); } r = strftime(buf, buf_size, "%B", &good_data); if (r == 0 || strncmp(buf, "May", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"B\": %s", buf); } r = strftime(buf, buf_size, "%c", &good_data); if (r == 0 || strncmp(buf, "Tue May 5 11:04:49 2015", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"c\": %s", buf); } r = strftime(buf, buf_size, "%d", &good_data); if (r == 0 || strncmp(buf, "05", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"d\": %s", buf); } r = strftime(buf, buf_size, "%D", &good_data); if (r == 0 || strncmp(buf, "05/05/15", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"D\": %s", buf); } r = strftime(buf, buf_size, "%e", &good_data); if (r == 0 || strncmp(buf, " 5", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"e\": %s", buf); } r = strftime(buf, buf_size, "%F", &good_data); if (r == 0 || strncmp(buf, "2015-05-05", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"F\": %s", buf); } r = strftime(buf, buf_size, "%g", &good_data); if (r == 0 || strncmp(buf, "15", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"f\": %s", buf); } r = strftime(buf, buf_size, "%G", &good_data); if (r == 0 || strncmp(buf, "2015", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"G\": %s", buf); } r = strftime(buf, buf_size, "%h", &good_data); if (r == 0 || strncmp(buf, "May", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"h\": %s", buf); } r = strftime(buf, buf_size, "%H", &good_data); if (r == 0 || strncmp(buf, "11", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"H\": %s", buf); } r = strftime(buf, buf_size, "%I", &good_data); if (r == 0 || strncmp(buf, "11", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"I\": %s", buf); } r = strftime(buf, buf_size, "%j", &good_data); if (r == 0 || strncmp(buf, "125", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"j\": %s", buf); } r = strftime(buf, buf_size, "%m", &good_data); if (r == 0 || strncmp(buf, "05", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"m\": %s", buf); } r = strftime(buf, buf_size, "%M", &good_data); if (r == 0 || strncmp(buf, "04", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"M\": %s", buf); } r = strftime(buf, buf_size, "%p", &good_data); if (r == 0 || strncmp(buf, "AM", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"p\": %s", buf); } r = strftime(buf, buf_size, "%r", &good_data); if (r == 0 || strncmp(buf, "11:04:49 AM", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"r\": %s", buf); } r = strftime(buf, buf_size, "%R", &good_data); if (r == 0 || strncmp(buf, "11:04", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"R\": %s", buf); } r = strftime(buf, buf_size, "%S", &good_data); if (r == 0 || strncmp(buf, "49", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"S\": %s", buf); } r = strftime(buf, buf_size, "%T", &good_data); if (r == 0 || strncmp(buf, "11:04:49", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"T\": %s", buf); } r = strftime(buf, buf_size, "%u", &good_data); if (r == 0 || strncmp(buf, "2", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"u\": %s", buf); } r = strftime(buf, buf_size, "%U", &good_data);
r = strftime(buf, buf_size, "%V", &good_data); if (r == 0 || strncmp(buf, "19", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"V\": %s", buf); } r = strftime(buf, buf_size, "%w", &good_data); if (r == 0 || strncmp(buf, "2", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"w\": %s", buf); } r = strftime(buf, buf_size, "%W", &good_data); if (r == 0 || strncmp(buf, "18", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"W\": %s", buf); } r = strftime(buf, buf_size, "%x", &good_data); if (r == 0 || strncmp(buf, "05/05/15", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"x\": %s", buf); } r = strftime(buf, buf_size, "%X", &good_data); if (r == 0 || strncmp(buf, "11:04:49", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"X\": %s", buf); } r = strftime(buf, buf_size, "%y", &good_data); if (r == 0 || strncmp(buf, "15", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"y\": %s", buf); } r = strftime(buf, buf_size, "%Y", &good_data); if (r == 0 || strncmp(buf, "2015", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"Y\": %s", buf); } // r = strftime(buf, buf_size, "%z", &good_data); // if (r == 0 || strncmp(buf, "", buf_size) != 0) { // APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"z\": %s", buf); // } // r = strftime(buf, buf_size, "%Z", &good_data); // if (r == 0 || strncmp(buf, "", buf_size) != 0) { // APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"Z\": %s", buf); // } } static void prv_test_invalid_data(void) { const int buf_size = 64; char buf[buf_size]; // Make sure the invalid structs don't crash us // These should all return 0, but many don't seem to be doing that strftime(buf, buf_size, "%a", &bad_data); strftime(buf, buf_size, "%A", &bad_data); strftime(buf, buf_size, "%b", &bad_data); strftime(buf, buf_size, "%B", &bad_data); strftime(buf, buf_size, "%c", &bad_data); strftime(buf, buf_size, "%d", &bad_data); strftime(buf, buf_size, "%D", &bad_data); strftime(buf, buf_size, "%e", &bad_data); strftime(buf, buf_size, "%F", &bad_data); strftime(buf, buf_size, "%g", &bad_data); strftime(buf, buf_size, "%G", &bad_data); strftime(buf, buf_size, "%h", &bad_data); strftime(buf, buf_size, "%H", &bad_data); strftime(buf, buf_size, "%I", &bad_data); strftime(buf, buf_size, "%j", &bad_data); strftime(buf, buf_size, "%m", &bad_data); strftime(buf, buf_size, "%M", &bad_data); strftime(buf, buf_size, "%p", &bad_data); strftime(buf, buf_size, "%r", &bad_data); strftime(buf, buf_size, "%R", &bad_data); strftime(buf, buf_size, "%S", &bad_data); strftime(buf, buf_size, "%T", &bad_data); strftime(buf, buf_size, "%u", &bad_data); strftime(buf, buf_size, "%U", &bad_data); strftime(buf, buf_size, "%V", &bad_data); strftime(buf, buf_size, "%w", &bad_data); strftime(buf, buf_size, "%W", &bad_data); strftime(buf, buf_size, "%x", &bad_data); strftime(buf, buf_size, "%X", &bad_data); strftime(buf, buf_size, "%y", &bad_data); strftime(buf, buf_size, "%Y", &bad_data); // strftime(buf, buf_size, "%z", &bad_data); // strftime(buf, buf_size, "%Z", &bad_data); } static void window_load(Window *window) { prv_test_valid_data(); prv_test_invalid_data(); Layer *window_layer = window_get_root_layer(window); result_layer = text_layer_create(GRect(0, 0, 144, 168)); text_layer_set_text(result_layer, "strftime() test. Check the app logs for details"); text_layer_set_font(result_layer, fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD)); layer_add_child(window_layer, text_layer_get_layer(result_layer)); } static void window_unload(Window *window) { text_layer_destroy(result_layer); } static void init(void) { window = window_create(); window_set_window_handlers(window, (WindowHandlers) { .load = window_load, .unload = window_unload, }); const bool animated = true; window_stack_push(window, a
if (r == 0 || strncmp(buf, "18", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"U\": %s", buf); }
<|repo_name|>pebble <|file_sep|>src/apps/strftime_test/src/strftime_test.c <|fim_prefix|>s expected r = strftime(buf, buf_size, "%a", &good_data); if (r == 0 || strncmp(buf, "Tue", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"a\": %s", buf); } r = strftime(buf, buf_size, "%A", &good_data); if (r == 0 || strncmp(buf, "Tuesday", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"A\": %s", buf); } r = strftime(buf, buf_size, "%b", &good_data); if (r == 0 || strncmp(buf, "May", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"b\": %s", buf); } r = strftime(buf, buf_size, "%B", &good_data); if (r == 0 || strncmp(buf, "May", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"B\": %s", buf); } r = strftime(buf, buf_size, "%c", &good_data); if (r == 0 || strncmp(buf, "Tue May 5 11:04:49 2015", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"c\": %s", buf); } r = strftime(buf, buf_size, "%d", &good_data); if (r == 0 || strncmp(buf, "05", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"d\": %s", buf); } r = strftime(buf, buf_size, "%D", &good_data); if (r == 0 || strncmp(buf, "05/05/15", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"D\": %s", buf); } r = strftime(buf, buf_size, "%e", &good_data); if (r == 0 || strncmp(buf, " 5", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"e\": %s", buf); } r = strftime(buf, buf_size, "%F", &good_data); if (r == 0 || strncmp(buf, "2015-05-05", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"F\": %s", buf); } r = strftime(buf, buf_size, "%g", &good_data); if (r == 0 || strncmp(buf, "15", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"f\": %s", buf); } r = strftime(buf, buf_size, "%G", &good_data); if (r == 0 || strncmp(buf, "2015", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"G\": %s", buf); } r = strftime(buf, buf_size, "%h", &good_data); if (r == 0 || strncmp(buf, "May", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"h\": %s", buf); } r = strftime(buf, buf_size, "%H", &good_data); if (r == 0 || strncmp(buf, "11", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"H\": %s", buf); } r = strftime(buf, buf_size, "%I", &good_data); if (r == 0 || strncmp(buf, "11", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"I\": %s", buf); } r = strftime(buf, buf_size, "%j", &good_data); if (r == 0 || strncmp(buf, "125", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"j\": %s", buf); } r = strftime(buf, buf_size, "%m", &good_data); if (r == 0 || strncmp(buf, "05", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"m\": %s", buf); } r = strftime(buf, buf_size, "%M", &good_data); if (r == 0 || strncmp(buf, "04", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"M\": %s", buf); } r = strftime(buf, buf_size, "%p", &good_data); if (r == 0 || strncmp(buf, "AM", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"p\": %s", buf); } r = strftime(buf, buf_size, "%r", &good_data); if (r == 0 || strncmp(buf, "11:04:49 AM", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"r\": %s", buf); } r = strftime(buf, buf_size, "%R", &good_data); if (r == 0 || strncmp(buf, "11:04", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"R\": %s", buf); } r = strftime(buf, buf_size, "%S", &good_data); if (r == 0 || strncmp(buf, "49", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"S\": %s", buf); } r = strftime(buf, buf_size, "%T", &good_data); if (r == 0 || strncmp(buf, "11:04:49", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"T\": %s", buf); } r = strftime(buf, buf_size, "%u", &good_data); if (r == 0 || strncmp(buf, "2", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"u\": %s", buf); } r = strftime(buf, buf_size, "%U", &good_data); <|fim_suffix|> r = strftime(buf, buf_size, "%V", &good_data); if (r == 0 || strncmp(buf, "19", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"V\": %s", buf); } r = strftime(buf, buf_size, "%w", &good_data); if (r == 0 || strncmp(buf, "2", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"w\": %s", buf); } r = strftime(buf, buf_size, "%W", &good_data); if (r == 0 || strncmp(buf, "18", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"W\": %s", buf); } r = strftime(buf, buf_size, "%x", &good_data); if (r == 0 || strncmp(buf, "05/05/15", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"x\": %s", buf); } r = strftime(buf, buf_size, "%X", &good_data); if (r == 0 || strncmp(buf, "11:04:49", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"X\": %s", buf); } r = strftime(buf, buf_size, "%y", &good_data); if (r == 0 || strncmp(buf, "15", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"y\": %s", buf); } r = strftime(buf, buf_size, "%Y", &good_data); if (r == 0 || strncmp(buf, "2015", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"Y\": %s", buf); } // r = strftime(buf, buf_size, "%z", &good_data); // if (r == 0 || strncmp(buf, "", buf_size) != 0) { // APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"z\": %s", buf); // } // r = strftime(buf, buf_size, "%Z", &good_data); // if (r == 0 || strncmp(buf, "", buf_size) != 0) { // APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"Z\": %s", buf); // } } static void prv_test_invalid_data(void) { const int buf_size = 64; char buf[buf_size]; // Make sure the invalid structs don't crash us // These should all return 0, but many don't seem to be doing that strftime(buf, buf_size, "%a", &bad_data); strftime(buf, buf_size, "%A", &bad_data); strftime(buf, buf_size, "%b", &bad_data); strftime(buf, buf_size, "%B", &bad_data); strftime(buf, buf_size, "%c", &bad_data); strftime(buf, buf_size, "%d", &bad_data); strftime(buf, buf_size, "%D", &bad_data); strftime(buf, buf_size, "%e", &bad_data); strftime(buf, buf_size, "%F", &bad_data); strftime(buf, buf_size, "%g", &bad_data); strftime(buf, buf_size, "%G", &bad_data); strftime(buf, buf_size, "%h", &bad_data); strftime(buf, buf_size, "%H", &bad_data); strftime(buf, buf_size, "%I", &bad_data); strftime(buf, buf_size, "%j", &bad_data); strftime(buf, buf_size, "%m", &bad_data); strftime(buf, buf_size, "%M", &bad_data); strftime(buf, buf_size, "%p", &bad_data); strftime(buf, buf_size, "%r", &bad_data); strftime(buf, buf_size, "%R", &bad_data); strftime(buf, buf_size, "%S", &bad_data); strftime(buf, buf_size, "%T", &bad_data); strftime(buf, buf_size, "%u", &bad_data); strftime(buf, buf_size, "%U", &bad_data); strftime(buf, buf_size, "%V", &bad_data); strftime(buf, buf_size, "%w", &bad_data); strftime(buf, buf_size, "%W", &bad_data); strftime(buf, buf_size, "%x", &bad_data); strftime(buf, buf_size, "%X", &bad_data); strftime(buf, buf_size, "%y", &bad_data); strftime(buf, buf_size, "%Y", &bad_data); // strftime(buf, buf_size, "%z", &bad_data); // strftime(buf, buf_size, "%Z", &bad_data); } static void window_load(Window *window) { prv_test_valid_data(); prv_test_invalid_data(); Layer *window_layer = window_get_root_layer(window); result_layer = text_layer_create(GRect(0, 0, 144, 168)); text_layer_set_text(result_layer, "strftime() test. Check the app logs for details"); text_layer_set_font(result_layer, fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD)); layer_add_child(window_layer, text_layer_get_layer(result_layer)); } static void window_unload(Window *window) { text_layer_destroy(result_layer); } static void init(void) { window = window_create(); window_set_window_handlers(window, (WindowHandlers) { .load = window_load, .unload = window_unload, }); const bool animated = true; window_stack_push(window, a<|fim_middle|>if (r == 0 || strncmp(buf, "18", buf_size) != 0) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error with \"U\": %s", buf); }<|endoftext|>
masked_node
call_expression
src/bluetooth-fw/da1468x/controller/main/src/connection.c
ion *connection, ConnectionFlag flag) { bool val; prv_lock(); { uint32_t bit = (1 << flag); val = ((connection->flags & bit) == bit); } prv_unlock(); return val; } bool connection_is_subscribed_to_connection_status_notifications(const Connection *connection) { return prv_get_flag(connection, ConnectionFlag_IsSubscribedToConnectionStatusNotifications); } bool connection_should_pin_address(const Connection *connection) { return prv_get_flag(connection, ConnectionFlag_ShouldPinAddress); } bool connection_should_auto_accept_re_pairing(const Connection *connection) { return prv_get_flag(connection, ConnectionFlag_ShouldAutoAcceptRePairing); } bool connection_is_reversed_ppogatt_enabled(const Connection *connection) { return prv_get_flag(connection, ConnectionFlag_IsReversedPPoGATTEnabled); } bool connection_is_subscribed_to_gatt_mtu_notifications(const Connection *connection) { return prv_get_flag(connection, ConnectionFlag_IsSubscribedToGattMtuNotifications); } bool connection_is_subscribed_to_conn_param_notifications(const Connection *connection) { return prv_get_flag(connection, ConnectionFlag_IsSubscribedToConnParamNotifications); } // // Setters // void connection_set_gateway(Connection *connection, bool is_gateway) { prv_lock(); { if (connection_is_valid(connection)) { connection->is_gateway = is_gateway; } } prv_unlock(); } static char prv_debug_char_for_flag(ConnectionFlag flag) { static const char s_debug_chars[] = { [ConnectionFlag_IsSubscribedToConnectionStatusNotifications] = 'S', [ConnectionFlag_IsSubscribedToGattMtuNotifications] = 'M', [ConnectionFlag_IsSubscribedToConnParamNotifications] = 'C', [ConnectionFlag_ShouldPinAddress] = 'P', [ConnectionFlag_ShouldAutoAcceptRePairing] = 'A', [ConnectionFlag_IsReversedPPoGATTEnabled] = 'R', }; return s_debug_chars[flag]; } static void prv_set_flag(Connection *connection, bool enabled, ConnectionFlag flag) { prv_lock(); { if (connection_is_valid(connection)) { PBL_LOG(LOG_LEVEL_DEBUG, "Changing connection flag: %c=%u", prv_debug_char_for_flag(flag), enabled); if (enabled) { connection->flags |= (1 << flag); } else { connection->flags &= ~(1 << flag); } } } prv_unlock(); } void connection_set_subscribed_to_connection_status_notifications( Connection *connection, bool is_subscribed) { prv_set_flag(connection, is_subscribed, ConnectionFlag_IsSubscribedToConnectionStatusNotifications); } void connection_set_subscribed_to_gatt_mtu_notifications( Connection *connection, bool is_subscribed) { prv_set_flag(connection, is_subscribed, ConnectionFlag_IsSubscribedToGattMtuNotifications); } void connection_set_subscribed_to_conn_param_notifications( Connection *connection, bool is_subscribed) { prv_set_flag(connection, is_subscribed, ConnectionFlag_IsSubscribedToConnParamNotifications); } void connection_set_should_pin_address(Connection *connection, bool should_pin_address) { prv_set_flag(connection, should_pin_address, ConnectionFlag_ShouldPinAddress); } void connection_set_should_auto_accept_re_pairing(Connection *connection, bool should_auto_accept_re_pairing) { prv_set_flag(connection, should_auto_accept_re_pairing, ConnectionFlag_ShouldAutoAcceptRePairing); } void connection_set_reversed_ppogatt_enabled(Connection *connection, bool is_reversed_ppogatt_enabled) { prv_set_flag(connection, is_reversed_ppogatt_enabled, ConnectionFlag_IsReversedPPoGATTEnabled); } void connection_set_last_pairing_result(uint16_t conn_idx, uint8_t result) { prv_lock(); { Connection *connection = connection_by_idx(conn_idx); if (connection) { connection->last_pairing_result = result; } } prv_unlock(); } void connection_set_ppogatt_wa_state(Connection *connection, PPoGATTWorkAroundState *state) {
; { connection->ppogatt_wa_state = state; } prv_unlock(); } void connection_set_conn_params(Connection *connection, const BleConnectionParams *params) { prv_lock(); { if (connection_is_valid(connection)) { connection->conn_params = *params; } } prv_unlock(); } void connection_update_address(Connection *connection, const BTDeviceInternal *updated_addr) { prv_lock(); { if (connection_is_valid(connection)) { connection->updated_addr = *updated_addr; connection->has_updated_addr = true; } } prv_unlock(); } // // Other functions // void connection_enqueue_gatt_op(Connection *connection, uintptr_t context_ref, GattRespDest resp_dest, GattOpType op_type) { prv_lock(); { GattOperation *node = kernel_malloc_check(sizeof(GattOperation)); *node = (GattOperation) { .object_ref = context_ref, .resp_dest = resp_dest, .op_type = op_type, }; connection->gatt_op_list = (GattOperation *) list_get_head(list_append((ListNode *)connection->gatt_op_list, (ListNode *)node)); } prv_unlock(); } bool connection_dequeue_gatt_op(Connection *connection, uintptr_t *context_ref, GattRespDest *resp_dest, GattOpType expected_op_type) { bool rv = true; prv_lock(); { GattOperation *tmp = connection->gatt_op_list; if (!tmp) { rv = false; goto unlock; } *context_ref = tmp->object_ref; *resp_dest = tmp->resp_dest; PBL_ASSERTN(tmp->op_type == expected_op_type); connection->gatt_op_list = (GattOperation *)list_pop_head((ListNode *)connection->gatt_op_list); kernel_free(tmp); } unlock: prv_unlock(); return rv; } bool connection_pop_gatt_op(Connection *connection) { bool rv = true; prv_lock(); { GattOperation *tmp_tail = (GattOperation *)list_get_tail((ListNode *)connection->gatt_op_list); if (!tmp_tail) { PBL_LOG(LOG_LEVEL_WARNING, "Gatt: Attempted to pop recent op when list empty"); PBL_ASSERTN(0); } connection->gatt_op_list = (GattOperation *) list_get_head(list_pop_tail((ListNode *)connection->gatt_op_list)); kernel_free(tmp_tail); } prv_unlock(); return rv; }
prv_lock()
<|repo_name|>pebble <|file_sep|>src/bluetooth-fw/da1468x/controller/main/src/connection.c <|fim_prefix|>ion *connection, ConnectionFlag flag) { bool val; prv_lock(); { uint32_t bit = (1 << flag); val = ((connection->flags & bit) == bit); } prv_unlock(); return val; } bool connection_is_subscribed_to_connection_status_notifications(const Connection *connection) { return prv_get_flag(connection, ConnectionFlag_IsSubscribedToConnectionStatusNotifications); } bool connection_should_pin_address(const Connection *connection) { return prv_get_flag(connection, ConnectionFlag_ShouldPinAddress); } bool connection_should_auto_accept_re_pairing(const Connection *connection) { return prv_get_flag(connection, ConnectionFlag_ShouldAutoAcceptRePairing); } bool connection_is_reversed_ppogatt_enabled(const Connection *connection) { return prv_get_flag(connection, ConnectionFlag_IsReversedPPoGATTEnabled); } bool connection_is_subscribed_to_gatt_mtu_notifications(const Connection *connection) { return prv_get_flag(connection, ConnectionFlag_IsSubscribedToGattMtuNotifications); } bool connection_is_subscribed_to_conn_param_notifications(const Connection *connection) { return prv_get_flag(connection, ConnectionFlag_IsSubscribedToConnParamNotifications); } // // Setters // void connection_set_gateway(Connection *connection, bool is_gateway) { prv_lock(); { if (connection_is_valid(connection)) { connection->is_gateway = is_gateway; } } prv_unlock(); } static char prv_debug_char_for_flag(ConnectionFlag flag) { static const char s_debug_chars[] = { [ConnectionFlag_IsSubscribedToConnectionStatusNotifications] = 'S', [ConnectionFlag_IsSubscribedToGattMtuNotifications] = 'M', [ConnectionFlag_IsSubscribedToConnParamNotifications] = 'C', [ConnectionFlag_ShouldPinAddress] = 'P', [ConnectionFlag_ShouldAutoAcceptRePairing] = 'A', [ConnectionFlag_IsReversedPPoGATTEnabled] = 'R', }; return s_debug_chars[flag]; } static void prv_set_flag(Connection *connection, bool enabled, ConnectionFlag flag) { prv_lock(); { if (connection_is_valid(connection)) { PBL_LOG(LOG_LEVEL_DEBUG, "Changing connection flag: %c=%u", prv_debug_char_for_flag(flag), enabled); if (enabled) { connection->flags |= (1 << flag); } else { connection->flags &= ~(1 << flag); } } } prv_unlock(); } void connection_set_subscribed_to_connection_status_notifications( Connection *connection, bool is_subscribed) { prv_set_flag(connection, is_subscribed, ConnectionFlag_IsSubscribedToConnectionStatusNotifications); } void connection_set_subscribed_to_gatt_mtu_notifications( Connection *connection, bool is_subscribed) { prv_set_flag(connection, is_subscribed, ConnectionFlag_IsSubscribedToGattMtuNotifications); } void connection_set_subscribed_to_conn_param_notifications( Connection *connection, bool is_subscribed) { prv_set_flag(connection, is_subscribed, ConnectionFlag_IsSubscribedToConnParamNotifications); } void connection_set_should_pin_address(Connection *connection, bool should_pin_address) { prv_set_flag(connection, should_pin_address, ConnectionFlag_ShouldPinAddress); } void connection_set_should_auto_accept_re_pairing(Connection *connection, bool should_auto_accept_re_pairing) { prv_set_flag(connection, should_auto_accept_re_pairing, ConnectionFlag_ShouldAutoAcceptRePairing); } void connection_set_reversed_ppogatt_enabled(Connection *connection, bool is_reversed_ppogatt_enabled) { prv_set_flag(connection, is_reversed_ppogatt_enabled, ConnectionFlag_IsReversedPPoGATTEnabled); } void connection_set_last_pairing_result(uint16_t conn_idx, uint8_t result) { prv_lock(); { Connection *connection = connection_by_idx(conn_idx); if (connection) { connection->last_pairing_result = result; } } prv_unlock(); } void connection_set_ppogatt_wa_state(Connection *connection, PPoGATTWorkAroundState *state) { <|fim_suffix|>; { connection->ppogatt_wa_state = state; } prv_unlock(); } void connection_set_conn_params(Connection *connection, const BleConnectionParams *params) { prv_lock(); { if (connection_is_valid(connection)) { connection->conn_params = *params; } } prv_unlock(); } void connection_update_address(Connection *connection, const BTDeviceInternal *updated_addr) { prv_lock(); { if (connection_is_valid(connection)) { connection->updated_addr = *updated_addr; connection->has_updated_addr = true; } } prv_unlock(); } // // Other functions // void connection_enqueue_gatt_op(Connection *connection, uintptr_t context_ref, GattRespDest resp_dest, GattOpType op_type) { prv_lock(); { GattOperation *node = kernel_malloc_check(sizeof(GattOperation)); *node = (GattOperation) { .object_ref = context_ref, .resp_dest = resp_dest, .op_type = op_type, }; connection->gatt_op_list = (GattOperation *) list_get_head(list_append((ListNode *)connection->gatt_op_list, (ListNode *)node)); } prv_unlock(); } bool connection_dequeue_gatt_op(Connection *connection, uintptr_t *context_ref, GattRespDest *resp_dest, GattOpType expected_op_type) { bool rv = true; prv_lock(); { GattOperation *tmp = connection->gatt_op_list; if (!tmp) { rv = false; goto unlock; } *context_ref = tmp->object_ref; *resp_dest = tmp->resp_dest; PBL_ASSERTN(tmp->op_type == expected_op_type); connection->gatt_op_list = (GattOperation *)list_pop_head((ListNode *)connection->gatt_op_list); kernel_free(tmp); } unlock: prv_unlock(); return rv; } bool connection_pop_gatt_op(Connection *connection) { bool rv = true; prv_lock(); { GattOperation *tmp_tail = (GattOperation *)list_get_tail((ListNode *)connection->gatt_op_list); if (!tmp_tail) { PBL_LOG(LOG_LEVEL_WARNING, "Gatt: Attempted to pop recent op when list empty"); PBL_ASSERTN(0); } connection->gatt_op_list = (GattOperation *) list_get_head(list_pop_tail((ListNode *)connection->gatt_op_list)); kernel_free(tmp_tail); } prv_unlock(); return rv; } <|fim_middle|>prv_lock()<|endoftext|>
prefix_only
argument_list
src/apps/localtime_gmtime_test/src/localtime_gmtime_test.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <pebble.h> static Window *window; static TextLayer *time_layer; static TextLayer *gmtime_layer; static TextLayer *localtime_layer; static void window_load(Window *window) { Layer *window_layer = window_get_root_layer(window); time_t the_time = time(NULL); // Time layer static char time_buf[32]; snprintf(time_buf, 32, "time: %u", (unsigned) the_time); time_layer = text_layer_create
(GRect(0, 0, 144, 168))
<|repo_name|>pebble <|file_sep|>src/apps/localtime_gmtime_test/src/localtime_gmtime_test.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <pebble.h> static Window *window; static TextLayer *time_layer; static TextLayer *gmtime_layer; static TextLayer *localtime_layer; static void window_load(Window *window) { Layer *window_layer = window_get_root_layer(window); time_t the_time = time(NULL); // Time layer static char time_buf[32]; snprintf(time_buf, 32, "time: %u", (unsigned) the_time); time_layer = text_layer_create<|fim_suffix|><|fim_middle|>(GRect(0, 0, 144, 168))<|endoftext|>
masked_node
call_expression
src/fw/apps/system_apps/timeline/timeline.c
om_card(void) { TimelineAppData *data = s_app_data; PBL_ASSERTN(data); if (!prv_set_state(data, TimelineAppStatePopCard)) { return NULL; } // Animation structure: // - Scheduled simultaneously // - Transition card to pin // - Move timeline layer from the left // - After completion // - Bounce back the timeline layer // - Move pin window to the right animation_unschedule(data->current_animation); timeline_layer_set_layouts_hidden(&data->timeline_layer, true); window_set_background_color(&data->timeline_window, GColorWhite); #if !PLATFORM_TINTIN TimelineLayout *pin_timeline_layout = timeline_layer_get_current_layout(&data->timeline_layer); if (pin_timeline_layout) { // animation the pin icon TimelineItemLayer *item_layer = &data->pin_window.item_detail_layer; timeline_layout_transition_card_to_pin(item_layer->timeline_layout, pin_timeline_layout); } #endif // animate the timeline layer from the left Layer *layer = &data->timeline_layer.layer; GPoint from_origin = { -layer->bounds.size.w, 0 }; Animation *layer_in = (Animation *)property_animation_create_bounds_origin(layer, &from_origin, &GPointZero); animation_set_duration(layer_in, TIMELINE_CARD_TRANSITION_MS / 2); animation_set_custom_interpolation(layer_in, interpolate_moook); animation_set_handlers(layer_in, (AnimationHandlers) { .stopped = prv_back_from_card_stopped, }, data); data->current_animation = layer_in; animation_schedule(layer_in); // animate the card layout timeline_pin_window_pop(&data->pin_window); return layer_in; } ///////////////////////////////////// // App boilerplate ///////////////////////////////////// static bool NOINLINE prv_setup_timeline_app(void) { TimelineAppData *data = app_malloc_check(sizeof(TimelineAppData)); s_app_data = data; *data = (TimelineAppData){}; data->blobdb_event_info = (EventServiceInfo) { .type = PEBBLE_BLOBDB_EVENT, .handler = prv_blobdb_event_handler, .context = data, }; event_service_client_subscribe(&data->blobdb_event_info); const TimelineArgs *args = process_manager_get_current_process_args(); Uuid app_uuid; sys_get_app_uuid(&app_uuid); if (uuid_equal(&app_uuid, &(Uuid)TIMELINE_PAST_UUID_INIT)) { data->timeline_model.direction = TimelineIterDirectionPast; } else if (args == NULL) { data->timeline_model.direction = TimelineIterDirectionFuture; } else { data->timeline_model.direction = args->direction; } // check if we were asked to launch into a specific item time_t now = rtc_get_time(); TimelineItem pin; bool launch_into_pin = false; if (args && args->launch_into_pin && !uuid_is_invalid(&args->pin_id) && pin_db_get(&args->pin_id, &pin) == S_SUCCESS) { launch_into_pin = true; if (!args->stay_in_list_view) { // Launching directly into the pin, change the direction to match data->timeline_model.direction = timeline_direction_for_item(&pin, data->timeline_model.timeline, now); } timeline_item_free_allocated_buffer(&pin); } timeline_model_init(now, &data->timeline_model); // if we're launching into a particular item, we iterate to it now if (launch_into_pin) { while (!uuid_equal(&timeline_model_get_current_state()->pin.header.id, &args->pin_id)) { data->launch_into_deep_pin = true; if (!timeline_model_iter_next(NULL, NULL)) { // for some reason we can't find the pin we were asked to launch into char uuid_buffer[UUID_STRING_BUFFER_LENGTH]; uuid_to_string(&args->pin_id, uuid_buffer); PBL_LOG(LOG_LEVEL_ERROR, "Asked to launch into pin but can't find it %s", uuid_buffer); launch_into_pin = false; data->launch_into_deep_pin = false; // we couldn't find the launch pin, go back to the present while (timeline_model_iter_prev(NULL, NULL)) {} break; } } } Window *window = &data->timeline_window; window_init(window,
); window_set_user_data(window, data); window_set_window_handlers(window, &(WindowHandlers) { .load = prv_timeline_window_load, .appear = prv_timeline_window_appear, .disappear = prv_timeline_window_disappear, .unload = prv_timeline_window_unload }); return (launch_into_pin && !(args && args->stay_in_list_view)); } T_STATIC void NOINLINE prv_init(void) { bool do_push_pin_window = prv_setup_timeline_app(); app_window_stack_push(&s_app_data->timeline_window, true /* animated */); if (do_push_pin_window) { prv_push_pin_window(s_app_data, timeline_model_get_current_state(), false /* animated */); } #if CAPABILITY_HAS_TIMELINE_PEEK if (!timeline_model_is_empty()) { timeline_layer_set_sidebar_width(&s_app_data->timeline_layer, timeline_layer_get_ideal_sidebar_width()); } #endif } static void NOINLINE prv_deinit(void) { prv_cleanup_timer(&s_app_data->intro_timer_id); prv_cleanup_timer(&s_app_data->inactive_timer_id); event_service_client_unsubscribe(&s_app_data->focus_event_info); event_service_client_unsubscribe(&s_app_data->blobdb_event_info); timeline_layer_deinit(&s_app_data->timeline_layer); timeline_model_deinit(); app_free(s_app_data); } static void prv_main(void) { prv_init(); app_event_loop(); prv_deinit(); } const PebbleProcessMd *timeline_get_app_info() { static const PebbleProcessMdSystem s_app_md = { .common = { .main_func = prv_main, // uuid: 79C76B48-6111-4E80-8DEB-3119EEBEF33E .uuid = {0x79, 0xC7, 0x6B, 0x48, 0x61, 0x11, 0x4E, 0x80, 0x8D, 0xEB, 0x31, 0x19, 0xEE, 0xBE, 0xF3, 0x3E}, .visibility = ProcessVisibilityHidden, }, .name = "Timeline", }; return &s_app_md.common; } const PebbleProcessMd *timeline_past_get_app_info() { static const PebbleProcessMdSystem s_app_md = { .common = { .main_func = prv_main, .uuid = TIMELINE_PAST_UUID_INIT, .visibility = ProcessVisibilityQuickLaunch, }, /// The title of Timeline Past in Quick Launch. If the translation is too long, cut out /// Timeline and only translate "Past". .name = i18n_noop("Timeline Past"), }; return &s_app_md.common; }
WINDOW_NAME("Timeline")
<|repo_name|>pebble <|file_sep|>src/fw/apps/system_apps/timeline/timeline.c <|fim_prefix|>om_card(void) { TimelineAppData *data = s_app_data; PBL_ASSERTN(data); if (!prv_set_state(data, TimelineAppStatePopCard)) { return NULL; } // Animation structure: // - Scheduled simultaneously // - Transition card to pin // - Move timeline layer from the left // - After completion // - Bounce back the timeline layer // - Move pin window to the right animation_unschedule(data->current_animation); timeline_layer_set_layouts_hidden(&data->timeline_layer, true); window_set_background_color(&data->timeline_window, GColorWhite); #if !PLATFORM_TINTIN TimelineLayout *pin_timeline_layout = timeline_layer_get_current_layout(&data->timeline_layer); if (pin_timeline_layout) { // animation the pin icon TimelineItemLayer *item_layer = &data->pin_window.item_detail_layer; timeline_layout_transition_card_to_pin(item_layer->timeline_layout, pin_timeline_layout); } #endif // animate the timeline layer from the left Layer *layer = &data->timeline_layer.layer; GPoint from_origin = { -layer->bounds.size.w, 0 }; Animation *layer_in = (Animation *)property_animation_create_bounds_origin(layer, &from_origin, &GPointZero); animation_set_duration(layer_in, TIMELINE_CARD_TRANSITION_MS / 2); animation_set_custom_interpolation(layer_in, interpolate_moook); animation_set_handlers(layer_in, (AnimationHandlers) { .stopped = prv_back_from_card_stopped, }, data); data->current_animation = layer_in; animation_schedule(layer_in); // animate the card layout timeline_pin_window_pop(&data->pin_window); return layer_in; } ///////////////////////////////////// // App boilerplate ///////////////////////////////////// static bool NOINLINE prv_setup_timeline_app(void) { TimelineAppData *data = app_malloc_check(sizeof(TimelineAppData)); s_app_data = data; *data = (TimelineAppData){}; data->blobdb_event_info = (EventServiceInfo) { .type = PEBBLE_BLOBDB_EVENT, .handler = prv_blobdb_event_handler, .context = data, }; event_service_client_subscribe(&data->blobdb_event_info); const TimelineArgs *args = process_manager_get_current_process_args(); Uuid app_uuid; sys_get_app_uuid(&app_uuid); if (uuid_equal(&app_uuid, &(Uuid)TIMELINE_PAST_UUID_INIT)) { data->timeline_model.direction = TimelineIterDirectionPast; } else if (args == NULL) { data->timeline_model.direction = TimelineIterDirectionFuture; } else { data->timeline_model.direction = args->direction; } // check if we were asked to launch into a specific item time_t now = rtc_get_time(); TimelineItem pin; bool launch_into_pin = false; if (args && args->launch_into_pin && !uuid_is_invalid(&args->pin_id) && pin_db_get(&args->pin_id, &pin) == S_SUCCESS) { launch_into_pin = true; if (!args->stay_in_list_view) { // Launching directly into the pin, change the direction to match data->timeline_model.direction = timeline_direction_for_item(&pin, data->timeline_model.timeline, now); } timeline_item_free_allocated_buffer(&pin); } timeline_model_init(now, &data->timeline_model); // if we're launching into a particular item, we iterate to it now if (launch_into_pin) { while (!uuid_equal(&timeline_model_get_current_state()->pin.header.id, &args->pin_id)) { data->launch_into_deep_pin = true; if (!timeline_model_iter_next(NULL, NULL)) { // for some reason we can't find the pin we were asked to launch into char uuid_buffer[UUID_STRING_BUFFER_LENGTH]; uuid_to_string(&args->pin_id, uuid_buffer); PBL_LOG(LOG_LEVEL_ERROR, "Asked to launch into pin but can't find it %s", uuid_buffer); launch_into_pin = false; data->launch_into_deep_pin = false; // we couldn't find the launch pin, go back to the present while (timeline_model_iter_prev(NULL, NULL)) {} break; } } } Window *window = &data->timeline_window; window_init(window, <|fim_suffix|>); window_set_user_data(window, data); window_set_window_handlers(window, &(WindowHandlers) { .load = prv_timeline_window_load, .appear = prv_timeline_window_appear, .disappear = prv_timeline_window_disappear, .unload = prv_timeline_window_unload }); return (launch_into_pin && !(args && args->stay_in_list_view)); } T_STATIC void NOINLINE prv_init(void) { bool do_push_pin_window = prv_setup_timeline_app(); app_window_stack_push(&s_app_data->timeline_window, true /* animated */); if (do_push_pin_window) { prv_push_pin_window(s_app_data, timeline_model_get_current_state(), false /* animated */); } #if CAPABILITY_HAS_TIMELINE_PEEK if (!timeline_model_is_empty()) { timeline_layer_set_sidebar_width(&s_app_data->timeline_layer, timeline_layer_get_ideal_sidebar_width()); } #endif } static void NOINLINE prv_deinit(void) { prv_cleanup_timer(&s_app_data->intro_timer_id); prv_cleanup_timer(&s_app_data->inactive_timer_id); event_service_client_unsubscribe(&s_app_data->focus_event_info); event_service_client_unsubscribe(&s_app_data->blobdb_event_info); timeline_layer_deinit(&s_app_data->timeline_layer); timeline_model_deinit(); app_free(s_app_data); } static void prv_main(void) { prv_init(); app_event_loop(); prv_deinit(); } const PebbleProcessMd *timeline_get_app_info() { static const PebbleProcessMdSystem s_app_md = { .common = { .main_func = prv_main, // uuid: 79C76B48-6111-4E80-8DEB-3119EEBEF33E .uuid = {0x79, 0xC7, 0x6B, 0x48, 0x61, 0x11, 0x4E, 0x80, 0x8D, 0xEB, 0x31, 0x19, 0xEE, 0xBE, 0xF3, 0x3E}, .visibility = ProcessVisibilityHidden, }, .name = "Timeline", }; return &s_app_md.common; } const PebbleProcessMd *timeline_past_get_app_info() { static const PebbleProcessMdSystem s_app_md = { .common = { .main_func = prv_main, .uuid = TIMELINE_PAST_UUID_INIT, .visibility = ProcessVisibilityQuickLaunch, }, /// The title of Timeline Past in Quick Launch. If the translation is too long, cut out /// Timeline and only translate "Past". .name = i18n_noop("Timeline Past"), }; return &s_app_md.common; } <|fim_middle|>WINDOW_NAME("Timeline")<|endoftext|>
masked_node
if_statement
src/fw/services/normal/analytics/analytics_heartbeat.c
cpy(location, data, size); } ///////// // Get int64_t analytics_heartbeat_get(AnalyticsHeartbeat *heartbeat, AnalyticsMetric metric) { uint8_t *location = prv_heartbeat_get_location(heartbeat, metric); return prv_location_get_value(location, analytics_metric_element_type(metric)); } int64_t analytics_heartbeat_get_array(AnalyticsHeartbeat *heartbeat, AnalyticsMetric metric, uint32_t index) { uint8_t *location = prv_heartbeat_get_array_location(heartbeat, metric, index); return prv_location_get_value(location, analytics_metric_element_type(metric)); } const Uuid *analytics_heartbeat_get_uuid(AnalyticsHeartbeat *heartbeat) { return (const Uuid*)prv_heartbeat_get_array_location(heartbeat, ANALYTICS_APP_METRIC_UUID, 0); } /////////////////// // Create / Clear AnalyticsHeartbeat *analytics_heartbeat_create(AnalyticsHeartbeatKind kind) { uint32_t size = sizeof(AnalyticsHeartbeat) + analytics_heartbeat_kind_data_size(kind); AnalyticsHeartbeat *heartbeat = kernel_malloc_check(size); heartbeat->kind = kind; analytics_heartbeat_clear(heartbeat); return heartbeat; } AnalyticsHeartbeat *analytics_heartbeat_device_create() { AnalyticsHeartbeat *hb = analytics_heartbeat_create(ANALYTICS_HEARTBEAT_KIND_DEVICE); analytics_heartbeat_set(hb, ANALYTICS_DEVICE_METRIC_BLOB_KIND, ANALYTICS_BLOB_KIND_DEVICE_HEARTBEAT); analytics_heartbeat_set(hb, ANALYTICS_DEVICE_METRIC_BLOB_VERSION, ANALYTICS_DEVICE_HEARTBEAT_BLOB_VERSION); return hb; } AnalyticsHeartbeat *analytics_heartbeat_app_create(const Uuid *uuid) { AnalyticsHeartbeat *hb = analytics_heartbeat_create(ANALYTICS_HEARTBEAT_KIND_APP); analytics_heartbeat_set_entire_array(hb, ANALYTICS_APP_METRIC_UUID, uuid); analytics_heartbeat_set(hb, ANALYTICS_APP_METRIC_BLOB_KIND, ANALYTICS_BLOB_KIND_APP_HEARTBEAT); analytics_heartbeat_set(hb, ANALYTICS_APP_METRIC_BLOB_VERSION, ANALYTICS_APP_HEARTBEAT_BLOB_VERSION); return hb; } void analytics_heartbeat_clear(AnalyticsHeartbeat *heartbeat) { AnalyticsHeartbeatKind kind = heartbeat->kind; uint32_t size = sizeof(AnalyticsHeartbeat) + analytics_heartbeat_kind_data_size(kind); memset(heartbeat, 0, size); heartbeat->kind = kind; } ////////////////// // Debug #ifdef ANALYTICS_DEBUG // Function to get the name of a macro given it's runtime value. (i.e. mapping // (1: "ANALYTICS_DEVICE_METRIC_MSG_ID"), // (2: "ANALYTICS_DEVICE_METRIC_VERSION"), // ... // ) #define CASE(name, ...) case name: return #name; static const char *prv_get_metric_name(AnalyticsMetric metric) { switch (metric) { ANALYTICS_METRIC_TABLE(CASE,CASE,CASE,,,,,,) default: return ""; } } #undef CASE static void prv_print_heartbeat(AnalyticsHeartbeat *heartbeat, AnalyticsMetric start, AnalyticsMetric end) { for (AnalyticsMetric metric = start + 1; metric < end; metric++) { const char *name = prv_get_metric_name(metric); if (!analytics_metric_is_array(metric)) { int64_t val = analytics_heartbeat_get(heartbeat, metric); if (val >= 0) { PBL_LOG(LOG_LEVEL_DEBUG, "%3" PRIu32 ": %s: %" PRIu32 " (0x%" PRIx32")", analytics_metric_offset(metric), name, (uint32_t)val, (uint32_t)val); } else { PBL_LOG(LOG_LEVEL_DEBUG, "%3" PRIu32 ": %s: %" PRId32 " (0x%" PRIx32")", analytics_metric_offset(metric), name, (int32_t)val, (int32_t)val); } continue; } const size_t BUF_LENGTH = 256; char buf[BUF_LENGTH]; uint32_t written = 0; for (uint32_t i = 0; i < analytics_metric_num_elements(metric); i++) { if (written > BUF_LENGTH) { PBL_LOG(LOG_LEVEL_DEBUG, "print buffer overflow by %lu bytes", BUF_LENGTH - written); continue; } int64_t val = analytics_heartbeat_get_array(heartbeat, metric, i); const char *sep = (i == 0 ? "" : ", ");
} PBL_LOG(LOG_LEVEL_DEBUG, "%3" PRIu32 ": %s: %s", analytics_metric_offset(metric), name, buf); } } void analytics_heartbeat_print(AnalyticsHeartbeat *heartbeat) { switch (heartbeat->kind) { case ANALYTICS_HEARTBEAT_KIND_DEVICE: PBL_LOG(LOG_LEVEL_DEBUG, "Device heartbeat:"); prv_print_heartbeat(heartbeat, ANALYTICS_DEVICE_METRIC_START, ANALYTICS_DEVICE_METRIC_END); break; case ANALYTICS_HEARTBEAT_KIND_APP: { const Uuid *uuid = analytics_heartbeat_get_uuid(heartbeat); char uuid_buf[UUID_STRING_BUFFER_LENGTH]; uuid_to_string(uuid, uuid_buf); PBL_LOG(LOG_LEVEL_DEBUG, "App heartbeat for %s:", uuid_buf); prv_print_heartbeat(heartbeat, ANALYTICS_APP_METRIC_START, ANALYTICS_APP_METRIC_END); break; } default: PBL_LOG(LOG_LEVEL_DEBUG, "Unable to print heartbeat: Unrecognized kind %d", heartbeat->kind); } } #else void analytics_heartbeat_print(AnalyticsHeartbeat *heartbeat) { PBL_LOG(LOG_LEVEL_DEBUG, "Turn on ANALYTICS_DEBUG to get heartbeat printing support."); } #endif
if (val >= 0) { written += snprintf(buf + written, BUF_LENGTH - written, "%s%" PRIu32 " (0x%" PRIx32 ")", sep, (uint32_t)val, (uint32_t)val); } else { written += snprintf(buf + written, BUF_LENGTH - written, "%s%" PRId32 " (0x%" PRIx32 ")", sep, (int32_t)val, (int32_t)val); }
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/analytics/analytics_heartbeat.c <|fim_prefix|>cpy(location, data, size); } ///////// // Get int64_t analytics_heartbeat_get(AnalyticsHeartbeat *heartbeat, AnalyticsMetric metric) { uint8_t *location = prv_heartbeat_get_location(heartbeat, metric); return prv_location_get_value(location, analytics_metric_element_type(metric)); } int64_t analytics_heartbeat_get_array(AnalyticsHeartbeat *heartbeat, AnalyticsMetric metric, uint32_t index) { uint8_t *location = prv_heartbeat_get_array_location(heartbeat, metric, index); return prv_location_get_value(location, analytics_metric_element_type(metric)); } const Uuid *analytics_heartbeat_get_uuid(AnalyticsHeartbeat *heartbeat) { return (const Uuid*)prv_heartbeat_get_array_location(heartbeat, ANALYTICS_APP_METRIC_UUID, 0); } /////////////////// // Create / Clear AnalyticsHeartbeat *analytics_heartbeat_create(AnalyticsHeartbeatKind kind) { uint32_t size = sizeof(AnalyticsHeartbeat) + analytics_heartbeat_kind_data_size(kind); AnalyticsHeartbeat *heartbeat = kernel_malloc_check(size); heartbeat->kind = kind; analytics_heartbeat_clear(heartbeat); return heartbeat; } AnalyticsHeartbeat *analytics_heartbeat_device_create() { AnalyticsHeartbeat *hb = analytics_heartbeat_create(ANALYTICS_HEARTBEAT_KIND_DEVICE); analytics_heartbeat_set(hb, ANALYTICS_DEVICE_METRIC_BLOB_KIND, ANALYTICS_BLOB_KIND_DEVICE_HEARTBEAT); analytics_heartbeat_set(hb, ANALYTICS_DEVICE_METRIC_BLOB_VERSION, ANALYTICS_DEVICE_HEARTBEAT_BLOB_VERSION); return hb; } AnalyticsHeartbeat *analytics_heartbeat_app_create(const Uuid *uuid) { AnalyticsHeartbeat *hb = analytics_heartbeat_create(ANALYTICS_HEARTBEAT_KIND_APP); analytics_heartbeat_set_entire_array(hb, ANALYTICS_APP_METRIC_UUID, uuid); analytics_heartbeat_set(hb, ANALYTICS_APP_METRIC_BLOB_KIND, ANALYTICS_BLOB_KIND_APP_HEARTBEAT); analytics_heartbeat_set(hb, ANALYTICS_APP_METRIC_BLOB_VERSION, ANALYTICS_APP_HEARTBEAT_BLOB_VERSION); return hb; } void analytics_heartbeat_clear(AnalyticsHeartbeat *heartbeat) { AnalyticsHeartbeatKind kind = heartbeat->kind; uint32_t size = sizeof(AnalyticsHeartbeat) + analytics_heartbeat_kind_data_size(kind); memset(heartbeat, 0, size); heartbeat->kind = kind; } ////////////////// // Debug #ifdef ANALYTICS_DEBUG // Function to get the name of a macro given it's runtime value. (i.e. mapping // (1: "ANALYTICS_DEVICE_METRIC_MSG_ID"), // (2: "ANALYTICS_DEVICE_METRIC_VERSION"), // ... // ) #define CASE(name, ...) case name: return #name; static const char *prv_get_metric_name(AnalyticsMetric metric) { switch (metric) { ANALYTICS_METRIC_TABLE(CASE,CASE,CASE,,,,,,) default: return ""; } } #undef CASE static void prv_print_heartbeat(AnalyticsHeartbeat *heartbeat, AnalyticsMetric start, AnalyticsMetric end) { for (AnalyticsMetric metric = start + 1; metric < end; metric++) { const char *name = prv_get_metric_name(metric); if (!analytics_metric_is_array(metric)) { int64_t val = analytics_heartbeat_get(heartbeat, metric); if (val >= 0) { PBL_LOG(LOG_LEVEL_DEBUG, "%3" PRIu32 ": %s: %" PRIu32 " (0x%" PRIx32")", analytics_metric_offset(metric), name, (uint32_t)val, (uint32_t)val); } else { PBL_LOG(LOG_LEVEL_DEBUG, "%3" PRIu32 ": %s: %" PRId32 " (0x%" PRIx32")", analytics_metric_offset(metric), name, (int32_t)val, (int32_t)val); } continue; } const size_t BUF_LENGTH = 256; char buf[BUF_LENGTH]; uint32_t written = 0; for (uint32_t i = 0; i < analytics_metric_num_elements(metric); i++) { if (written > BUF_LENGTH) { PBL_LOG(LOG_LEVEL_DEBUG, "print buffer overflow by %lu bytes", BUF_LENGTH - written); continue; } int64_t val = analytics_heartbeat_get_array(heartbeat, metric, i); const char *sep = (i == 0 ? "" : ", "); <|fim_suffix|> } PBL_LOG(LOG_LEVEL_DEBUG, "%3" PRIu32 ": %s: %s", analytics_metric_offset(metric), name, buf); } } void analytics_heartbeat_print(AnalyticsHeartbeat *heartbeat) { switch (heartbeat->kind) { case ANALYTICS_HEARTBEAT_KIND_DEVICE: PBL_LOG(LOG_LEVEL_DEBUG, "Device heartbeat:"); prv_print_heartbeat(heartbeat, ANALYTICS_DEVICE_METRIC_START, ANALYTICS_DEVICE_METRIC_END); break; case ANALYTICS_HEARTBEAT_KIND_APP: { const Uuid *uuid = analytics_heartbeat_get_uuid(heartbeat); char uuid_buf[UUID_STRING_BUFFER_LENGTH]; uuid_to_string(uuid, uuid_buf); PBL_LOG(LOG_LEVEL_DEBUG, "App heartbeat for %s:", uuid_buf); prv_print_heartbeat(heartbeat, ANALYTICS_APP_METRIC_START, ANALYTICS_APP_METRIC_END); break; } default: PBL_LOG(LOG_LEVEL_DEBUG, "Unable to print heartbeat: Unrecognized kind %d", heartbeat->kind); } } #else void analytics_heartbeat_print(AnalyticsHeartbeat *heartbeat) { PBL_LOG(LOG_LEVEL_DEBUG, "Turn on ANALYTICS_DEBUG to get heartbeat printing support."); } #endif <|fim_middle|>if (val >= 0) { written += snprintf(buf + written, BUF_LENGTH - written, "%s%" PRIu32 " (0x%" PRIx32 ")", sep, (uint32_t)val, (uint32_t)val); } else { written += snprintf(buf + written, BUF_LENGTH - written, "%s%" PRId32 " (0x%" PRIx32 ")", sep, (int32_t)val, (int32_t)val); }<|endoftext|>
masked_node
call_expression
tests/fw/graphics/test_graphics_circle.c
qual_gpoint(result, GPoint(5, 0)); // 270 (90 * 3) degrees should be (-5, 0) result = gpoint_from_polar_internal(&origin_center, radius, (TRIG_MAX_ANGLE * 3 / 4)); cl_assert_equal_gpoint(result, GPoint(-5, 0)); const GPoint offset_center = GPoint(1, 1); // 90 degrees should be (6, 1) result = gpoint_from_polar_internal(&offset_center, radius, (TRIG_MAX_ANGLE / 4)); cl_assert_equal_gpoint(result, GPoint(6, 1)); // 270 (90 * 3) degrees should be (-4, 1) result = gpoint_from_polar_internal(&offset_center, radius, (TRIG_MAX_ANGLE * 3 / 4)); cl_assert_equal_gpoint(result, GPoint(-4, 1)); } void test_graphics_circle__gpoint_from_polar_normalizes_input_angles(void) { const uint16_t radius = 5; const GPoint center = GPointZero; GPoint result; // -180 degrees should be (0, 5) result = gpoint_from_polar_internal(&center, radius, -(TRIG_MAX_ANGLE / 2)); cl_assert_equal_gpoint(result, GPoint(0, 5)); // -90 degrees should be (-5, 0) result = gpoint_from_polar_internal(&center, radius, -(TRIG_MAX_ANGLE / 4)); cl_assert_equal_gpoint(result, GPoint(-5, 0)); // -450 degrees (-90 * 5 -> -90) should be (-5, 0) result = gpoint_from_polar_internal(&center, radius, -(TRIG_MAX_ANGLE * 5 / 4)); cl_assert_equal_gpoint(result, GPoint(-5, 0)); // 450 degrees (90 * 5 -> 90) should be (0, 5) result = gpoint_from_polar_internal(&center, radius, (TRIG_MAX_ANGLE * 5 / 4)); cl_assert_equal_gpoint(result, GPoint(5, 0)); // 360 degrees (-> 0 degrees) should be (0, -5) result = gpoint_from_polar_internal(&center, radius, TRIG_MAX_ANGLE); cl_assert_equal_gpoint(result, GPoint(0, -5)); // -360 degrees (-> 0 degrees) should be (0, -5) result = gpoint_from_polar_internal(&center, radius, -TRIG_MAX_ANGLE); cl_assert_equal_gpoint(result, GPoint(0, -5)); } void test_graphics_circle__gpoint_from_polar_correct_scale(void) { // edge cases are covered above, this test only verifies that // the internal implementation correctly scales GPoint result = gpoint_from_polar(GRect(0, 0, 10, 10), GOvalScaleModeFillCircle, 0); cl_assert_equal_gpoint(result, GPoint(4, 0)); } void test_graphics_circle__grect_centered_from_polar(void) { GOvalScaleMode mode = GOvalScaleModeFillCircle; // Basic container rect with GPointZero origin const GRect container_rect1 = GRect(0, 0, 10, 10); const GRect resulting_rect1 = grect_centered_from_polar(container_rect1, mode, 0, GSize(3, 5)); cl_assert_equal_grect(resulting_rect1, GRect(3, -2, 3, 5)); // Container rect is offset from GPointZero const GRect container_rect2 = GRect(2, 2, 4, 4); const GRect resulting_rect2 = grect_centered_from_polar(container_rect2, mode, 0, GSize(2, 4)); cl_assert_equal_grect(resulting_rect2, GRect(3, 0, 2, 4)); // Odd-length width and height for container rect, 180 degree angle const GRect container_rect3 = GRect(2, 2, 5, 5); const GRect resulting_rect3 = grect_centered_from_polar(container_rect3, mode, DEG_TO_TRIGANGLE(180), GSize(2, 4)); cl_assert_equal_grect(resulting_rect3, GRect(3, 4, 2, 4)); } void test_graphics_circle__grect_centered_internal(void) { GPointPrecise p1 = GPointPrecise(0, 0); // GRectZero + standardize cl_assert_equal_grect(GRect(0, 0, 0, 0), grect_centered_internal(&p1, GSize(0, 0))); cl_assert_equal_grect(GRect(0, -1, 1, 2), grect_centered_internal(&p1, GSize(-1, -2))); // handles fixed point cl_assert_equal_grect(GRect(-1, -1, 2, 2), grect_centered_internal(&p1, GSize(2, 2))); p1.x.raw_value += FIXED_S16_3_HALF.raw_value; cl_assert_equal_grect(GRect(0, -1, 2, 2), grect_centered_internal(&p1, GSize(2, 2))); // Repeat for an offset center point GPointPrecise p2 = GPointPreciseFromGPoint(GPoint(5, 5)); // GRectZero + standardize cl_assert_equal_grect(GRect(5, 5, 0, 0), grect_centered_internal(&p2, GSize(0, 0))); cl_assert_equal_grect(GRect(5, 4, 1, 2), grect_centered_internal(&p2, GSize(-1, -2))); // handles fixed point cl_assert_equal_grect(GRect(4, 4, 2, 2), grect_centered_internal(&p2,
)); p2.x.raw_value += FIXED_S16_3_HALF.raw_value; cl_assert_equal_grect(GRect(5, 4, 2, 2), grect_centered_internal(&p2, GSize(2, 2))); // Repeat for a positive offset center point with 0.5 fractions GPointPrecise p3 = GPointPreciseFromGPoint(GPoint(5, 5)); p3.x.raw_value += FIXED_S16_3_HALF.raw_value; p3.y.raw_value += FIXED_S16_3_HALF.raw_value; // GRectZero + standardize cl_assert_equal_grect(GRect(6, 6, 0, 0), grect_centered_internal(&p3, GSize(0, 0))); cl_assert_equal_grect(GRect(5, 5, 1, 2), grect_centered_internal(&p3, GSize(-1, -2))); // handles fixed point cl_assert_equal_grect(GRect(5, 5, 2, 2), grect_centered_internal(&p3, GSize(2, 2))); p3.x.raw_value += FIXED_S16_3_HALF.raw_value; cl_assert_equal_grect(GRect(5, 5, 2, 2), grect_centered_internal(&p3, GSize(2, 2))); // Repeat for a negative offset center point with 0.5 fractions GPointPrecise p4 = GPointPreciseFromGPoint(GPoint(-5, -5)); p4.x.raw_value -= FIXED_S16_3_HALF.raw_value; p4.y.raw_value -= FIXED_S16_3_HALF.raw_value; // GRectZero + standardize cl_assert_equal_grect(GRect(-5, -5, 0, 0), grect_centered_internal(&p4, GSize(0, 0))); cl_assert_equal_grect(GRect(-6, -6, 1, 2), grect_centered_internal(&p4, GSize(-1, -2))); // handles fixed point cl_assert_equal_grect(GRect(-6, -6, 2, 2), grect_centered_internal(&p4, GSize(2, 2))); p4.x.raw_value += FIXED_S16_3_HALF.raw_value; cl_assert_equal_grect(GRect(-6, -6, 2, 2), grect_centered_internal(&p4, GSize(2, 2))); } #define cl_assert_fixedS16_3(v, f) \ cl_assert_equal_i((v).raw_value, (int)((f) * FIXED_S16_3_ONE.raw_value)) #define cl_assert_gpoint_precise(p, px, py) \ do { \ cl_assert_fixedS16_3(p.x, px); \ cl_assert_fixedS16_3(p.y, py); \ } while(0) void test_graphics_circle__grect_polar_calc_values_handles_null(void) { GPointPrecise center = {}; Fixed_S16_3 radius = {}; const GRect r = GRect(0, 0, 3, 5); const GOvalScaleMode mode = GOvalScaleModeFitCircle; grect_polar_calc_values(&r, mode, NULL, NULL); grect_polar_calc_values(&r, mode, &center, NULL); grect_polar_calc_values(&r, mode, NULL, &radius); cl_assert_gpoint_precise(center, 1, 2); cl_assert_fixedS16_3(radius, 1); grect_polar_calc_values(NULL, mode, &center, &radius); cl_assert_gpoint_precise(center, 1, 2); cl_assert_fixedS16_3(radius, 1); } void test_graphics_circle__grect_polar_calc_values_edge_cases(void) { GPointPrecise center = {}; Fixed_S16_3 radius = {}; const GOvalScaleMode mode = GOvalScaleModeFillCircle; GRect r = GRect(0, 5, 0, 0); grect_polar_calc_values(&r, mode, &center, &radius); cl_assert_gpoint_precise(center, 0, 5); cl_assert_fixedS16_3(radius, 0); // 1 pixel width means radius of 0 r = GRect(-1, -5, 1, 1); grect_polar_calc_values(&r, mode, &center, &radius); cl_assert_gpoint_precise(center, -1, -5); cl_assert_fixedS16_3(radius, 0); // 2 pixel width means: center is 1px from side, 0.5 pixels to center of outer pixels r = GRect(-1, -5, 2, 2); grect_polar_calc_values(&r, mode, &center, &radius); cl_assert_gpoint_precise(center, -0.5, -4.5); cl_assert_fixedS16_3(radius, 0.5); } void test_graphics_circle__grect_polar_calc_values_standardizes(void) { GPointPrecise center = {}; Fixed_S16_3 radius = {}; const GOvalScaleMode mode = GOvalScaleModeFitCircle; GRect r = GRect(0, 0, 10, 20); grect_polar_calc_values(&r, mode, &center, &radius); cl_assert_gpoint_precise(center, 4.5, 9.5); cl_assert_fixedS16_3(radius, 4.5); r = GRect(0, 0, -10, -20); grect_polar_calc_values(&r, mode, &center, &radius); cl_assert_gpoint_precise(center, -5.5, -10.5); cl_assert_fixedS16_3(radius, 4.5); } void test_graphics_circle__grect_polar_calc_values_square(void) { GPointPrecise center = {}; Fixed_S16_3 radius = {}; GRect r = GRect(0, 0, 5, 5); GOvalScaleMode mode = GOvalScaleModeFitCircle; // irrelevant as we deal with squares grect_polar_calc_values(&r, mode, &center, &radius); cl_assert_gpoint_precise(center, 2, 2); cl_assert_fixedS16_3(radius, 2); r = GRect(0, 0, 6, 6); gre
GSize(2, 2)
<|repo_name|>pebble <|file_sep|>tests/fw/graphics/test_graphics_circle.c <|fim_prefix|>qual_gpoint(result, GPoint(5, 0)); // 270 (90 * 3) degrees should be (-5, 0) result = gpoint_from_polar_internal(&origin_center, radius, (TRIG_MAX_ANGLE * 3 / 4)); cl_assert_equal_gpoint(result, GPoint(-5, 0)); const GPoint offset_center = GPoint(1, 1); // 90 degrees should be (6, 1) result = gpoint_from_polar_internal(&offset_center, radius, (TRIG_MAX_ANGLE / 4)); cl_assert_equal_gpoint(result, GPoint(6, 1)); // 270 (90 * 3) degrees should be (-4, 1) result = gpoint_from_polar_internal(&offset_center, radius, (TRIG_MAX_ANGLE * 3 / 4)); cl_assert_equal_gpoint(result, GPoint(-4, 1)); } void test_graphics_circle__gpoint_from_polar_normalizes_input_angles(void) { const uint16_t radius = 5; const GPoint center = GPointZero; GPoint result; // -180 degrees should be (0, 5) result = gpoint_from_polar_internal(&center, radius, -(TRIG_MAX_ANGLE / 2)); cl_assert_equal_gpoint(result, GPoint(0, 5)); // -90 degrees should be (-5, 0) result = gpoint_from_polar_internal(&center, radius, -(TRIG_MAX_ANGLE / 4)); cl_assert_equal_gpoint(result, GPoint(-5, 0)); // -450 degrees (-90 * 5 -> -90) should be (-5, 0) result = gpoint_from_polar_internal(&center, radius, -(TRIG_MAX_ANGLE * 5 / 4)); cl_assert_equal_gpoint(result, GPoint(-5, 0)); // 450 degrees (90 * 5 -> 90) should be (0, 5) result = gpoint_from_polar_internal(&center, radius, (TRIG_MAX_ANGLE * 5 / 4)); cl_assert_equal_gpoint(result, GPoint(5, 0)); // 360 degrees (-> 0 degrees) should be (0, -5) result = gpoint_from_polar_internal(&center, radius, TRIG_MAX_ANGLE); cl_assert_equal_gpoint(result, GPoint(0, -5)); // -360 degrees (-> 0 degrees) should be (0, -5) result = gpoint_from_polar_internal(&center, radius, -TRIG_MAX_ANGLE); cl_assert_equal_gpoint(result, GPoint(0, -5)); } void test_graphics_circle__gpoint_from_polar_correct_scale(void) { // edge cases are covered above, this test only verifies that // the internal implementation correctly scales GPoint result = gpoint_from_polar(GRect(0, 0, 10, 10), GOvalScaleModeFillCircle, 0); cl_assert_equal_gpoint(result, GPoint(4, 0)); } void test_graphics_circle__grect_centered_from_polar(void) { GOvalScaleMode mode = GOvalScaleModeFillCircle; // Basic container rect with GPointZero origin const GRect container_rect1 = GRect(0, 0, 10, 10); const GRect resulting_rect1 = grect_centered_from_polar(container_rect1, mode, 0, GSize(3, 5)); cl_assert_equal_grect(resulting_rect1, GRect(3, -2, 3, 5)); // Container rect is offset from GPointZero const GRect container_rect2 = GRect(2, 2, 4, 4); const GRect resulting_rect2 = grect_centered_from_polar(container_rect2, mode, 0, GSize(2, 4)); cl_assert_equal_grect(resulting_rect2, GRect(3, 0, 2, 4)); // Odd-length width and height for container rect, 180 degree angle const GRect container_rect3 = GRect(2, 2, 5, 5); const GRect resulting_rect3 = grect_centered_from_polar(container_rect3, mode, DEG_TO_TRIGANGLE(180), GSize(2, 4)); cl_assert_equal_grect(resulting_rect3, GRect(3, 4, 2, 4)); } void test_graphics_circle__grect_centered_internal(void) { GPointPrecise p1 = GPointPrecise(0, 0); // GRectZero + standardize cl_assert_equal_grect(GRect(0, 0, 0, 0), grect_centered_internal(&p1, GSize(0, 0))); cl_assert_equal_grect(GRect(0, -1, 1, 2), grect_centered_internal(&p1, GSize(-1, -2))); // handles fixed point cl_assert_equal_grect(GRect(-1, -1, 2, 2), grect_centered_internal(&p1, GSize(2, 2))); p1.x.raw_value += FIXED_S16_3_HALF.raw_value; cl_assert_equal_grect(GRect(0, -1, 2, 2), grect_centered_internal(&p1, GSize(2, 2))); // Repeat for an offset center point GPointPrecise p2 = GPointPreciseFromGPoint(GPoint(5, 5)); // GRectZero + standardize cl_assert_equal_grect(GRect(5, 5, 0, 0), grect_centered_internal(&p2, GSize(0, 0))); cl_assert_equal_grect(GRect(5, 4, 1, 2), grect_centered_internal(&p2, GSize(-1, -2))); // handles fixed point cl_assert_equal_grect(GRect(4, 4, 2, 2), grect_centered_internal(&p2, <|fim_suffix|>)); p2.x.raw_value += FIXED_S16_3_HALF.raw_value; cl_assert_equal_grect(GRect(5, 4, 2, 2), grect_centered_internal(&p2, GSize(2, 2))); // Repeat for a positive offset center point with 0.5 fractions GPointPrecise p3 = GPointPreciseFromGPoint(GPoint(5, 5)); p3.x.raw_value += FIXED_S16_3_HALF.raw_value; p3.y.raw_value += FIXED_S16_3_HALF.raw_value; // GRectZero + standardize cl_assert_equal_grect(GRect(6, 6, 0, 0), grect_centered_internal(&p3, GSize(0, 0))); cl_assert_equal_grect(GRect(5, 5, 1, 2), grect_centered_internal(&p3, GSize(-1, -2))); // handles fixed point cl_assert_equal_grect(GRect(5, 5, 2, 2), grect_centered_internal(&p3, GSize(2, 2))); p3.x.raw_value += FIXED_S16_3_HALF.raw_value; cl_assert_equal_grect(GRect(5, 5, 2, 2), grect_centered_internal(&p3, GSize(2, 2))); // Repeat for a negative offset center point with 0.5 fractions GPointPrecise p4 = GPointPreciseFromGPoint(GPoint(-5, -5)); p4.x.raw_value -= FIXED_S16_3_HALF.raw_value; p4.y.raw_value -= FIXED_S16_3_HALF.raw_value; // GRectZero + standardize cl_assert_equal_grect(GRect(-5, -5, 0, 0), grect_centered_internal(&p4, GSize(0, 0))); cl_assert_equal_grect(GRect(-6, -6, 1, 2), grect_centered_internal(&p4, GSize(-1, -2))); // handles fixed point cl_assert_equal_grect(GRect(-6, -6, 2, 2), grect_centered_internal(&p4, GSize(2, 2))); p4.x.raw_value += FIXED_S16_3_HALF.raw_value; cl_assert_equal_grect(GRect(-6, -6, 2, 2), grect_centered_internal(&p4, GSize(2, 2))); } #define cl_assert_fixedS16_3(v, f) \ cl_assert_equal_i((v).raw_value, (int)((f) * FIXED_S16_3_ONE.raw_value)) #define cl_assert_gpoint_precise(p, px, py) \ do { \ cl_assert_fixedS16_3(p.x, px); \ cl_assert_fixedS16_3(p.y, py); \ } while(0) void test_graphics_circle__grect_polar_calc_values_handles_null(void) { GPointPrecise center = {}; Fixed_S16_3 radius = {}; const GRect r = GRect(0, 0, 3, 5); const GOvalScaleMode mode = GOvalScaleModeFitCircle; grect_polar_calc_values(&r, mode, NULL, NULL); grect_polar_calc_values(&r, mode, &center, NULL); grect_polar_calc_values(&r, mode, NULL, &radius); cl_assert_gpoint_precise(center, 1, 2); cl_assert_fixedS16_3(radius, 1); grect_polar_calc_values(NULL, mode, &center, &radius); cl_assert_gpoint_precise(center, 1, 2); cl_assert_fixedS16_3(radius, 1); } void test_graphics_circle__grect_polar_calc_values_edge_cases(void) { GPointPrecise center = {}; Fixed_S16_3 radius = {}; const GOvalScaleMode mode = GOvalScaleModeFillCircle; GRect r = GRect(0, 5, 0, 0); grect_polar_calc_values(&r, mode, &center, &radius); cl_assert_gpoint_precise(center, 0, 5); cl_assert_fixedS16_3(radius, 0); // 1 pixel width means radius of 0 r = GRect(-1, -5, 1, 1); grect_polar_calc_values(&r, mode, &center, &radius); cl_assert_gpoint_precise(center, -1, -5); cl_assert_fixedS16_3(radius, 0); // 2 pixel width means: center is 1px from side, 0.5 pixels to center of outer pixels r = GRect(-1, -5, 2, 2); grect_polar_calc_values(&r, mode, &center, &radius); cl_assert_gpoint_precise(center, -0.5, -4.5); cl_assert_fixedS16_3(radius, 0.5); } void test_graphics_circle__grect_polar_calc_values_standardizes(void) { GPointPrecise center = {}; Fixed_S16_3 radius = {}; const GOvalScaleMode mode = GOvalScaleModeFitCircle; GRect r = GRect(0, 0, 10, 20); grect_polar_calc_values(&r, mode, &center, &radius); cl_assert_gpoint_precise(center, 4.5, 9.5); cl_assert_fixedS16_3(radius, 4.5); r = GRect(0, 0, -10, -20); grect_polar_calc_values(&r, mode, &center, &radius); cl_assert_gpoint_precise(center, -5.5, -10.5); cl_assert_fixedS16_3(radius, 4.5); } void test_graphics_circle__grect_polar_calc_values_square(void) { GPointPrecise center = {}; Fixed_S16_3 radius = {}; GRect r = GRect(0, 0, 5, 5); GOvalScaleMode mode = GOvalScaleModeFitCircle; // irrelevant as we deal with squares grect_polar_calc_values(&r, mode, &center, &radius); cl_assert_gpoint_precise(center, 2, 2); cl_assert_fixedS16_3(radius, 2); r = GRect(0, 0, 6, 6); gre<|fim_middle|>GSize(2, 2)<|endoftext|>
masked_node
call_expression
tests/fw/apps/watch/kickstart/test_kickstart.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apps/watch/kickstart/kickstart.h" #include "popups/timeline/peek.h" #include "applib/ui/window_private.h" #include "fw/graphics/util.h" #include "util/size.h" #include "clar.h" extern void prv_window_load_handler(Window *window); extern void prv_window_unload_handler(Window *window); extern void prv_set_unobstructed_area_height(int16_t height); extern void prv_set_data(KickstartData *data, int32_t current_steps, int32_t typical_steps, int32_t daily_steps_avg, int32_t current_bpm); // Fakes ///////////////////// #include "fake_pbl_std.h" #include "fake_spi_flash.h" #include "fixtures/load_test_resources.h" static bool s_clock_is_24h_style = false; bool clock_is_24h_style(void) { return s_clock_is_24h_style; } // Stubs ///////////////////// #include "stubs_analytics.h" #include "stubs_app.h" #include "stubs_app_install_manager.h" #include "stubs_app_timer.h" #include "stubs_app_window_stack.h" #include "stubs_bootbits.h" #include "stubs_click.h" #include "stubs_event_service_client.h" #include "stubs_health_service.h" #include "stubs_layer.h" #include "stubs_logging.h" #include "stubs_memory_layout.h" #include "stubs_mutex.h" #include "stubs_passert.h" #include "stubs_pbl_malloc.h" #include "stubs_pebble_process_info.h" #include "stubs_pebble_tasks.h" #include "stubs_process_manager.h" #include "stubs_prompt.h" #include "stubs_serial.h" #include "stubs_shell_prefs.h" #include "stubs_sleep.h" #include "stubs_syscalls.h" #include "stubs_task_watchdog.h" #include "stubs_text_layer_flow.h" #include "stubs_vibes.h" #include "stubs_window_manager.h" #include "stubs_window_stack.h" void tick_timer_service_subscribe(TimeUnits tick_units, TickHandler handler) {} void tick_timer_service_unsubscribe(void) {} // Setup and Teardown //////////////////////////////////// static GContext s_ctx; static FrameBuffer s_fb; static KickstartData s_data; GContext *graphics_context_get_current_context(void) { return &s_ctx; } void test_kickstart__initialize(void) { // Setup graphics context framebuffer_init(&s_fb, &(GSize) {DISP_COLS, DISP_ROWS}); framebuffer_clear(&s_fb); graphics_context_init(&s_ctx, &s_fb, GContextInitializationMode_App); s_app_state_get_graphics_context = &s_ctx; // Setup resources fake_spi_flash_init(0 /* offset */, 0x1000000 /* length */); pfs_init(false /* run filesystem check */); pfs_format(true /* write erase headers */); load_resource_fixture_in_flash(RESOURCES_FIXTURE_PATH, SYSTEM_RESOURCES_FIXTURE_NAME, false /* is_next */); resource_init(); // Reset data prv_set_data(&s_data, 0, 0, 0, 0);
; s_clock_is_24h_style = false; // Init window window_init(&s_data.window, WINDOW_NAME("Kickstart")); window_set_user_data(&s_data.window, &s_data); window_set_window_handlers(&s_data.window, &(WindowHandlers){ .load = prv_window_load_handler, .unload = prv_window_unload_handler, }); } void test_kickstart__cleanup(void) { window_deinit(&s_data.window); } // Tests ////////////////////// void test_kickstart__render_no_data(void) { window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_kickstart__render_obstructed_area(void) { #if !PBL_ROUND prv_set_unobstructed_area_height(TIMELINE_PEEK_HEIGHT); prv_set_data(&s_data, 5543, 6500, 8000, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); #endif } void test_kickstart__render_steps_above_typical(void) { prv_set_data(&s_data, 3528, 2500, 8000, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_kickstart__render_steps_below_typical(void) { prv_set_data(&s_data, 5543, 6500, 8000, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_kickstart__render_steps_above_daily_avg(void) { prv_set_data(&s_data, 10323, 7500, 8000, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_kickstart__render_hr_bpm(void) { #if (PLATFORM_SILK || PLATFORM_ROBERT) prv_set_data(&s_data, 10323, 7500, 13000, 82); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); #endif } void test_kickstart__render_hr_bpm_obstructed(void) { #if (PLATFORM_SILK || PLATFORM_ROBERT) prv_set_data(&s_data, 10323, 7500, 13000, 82); prv_set_unobstructed_area_height(TIMELINE_PEEK_HEIGHT); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); #endif } void test_kickstart__render_steps_above_daily_avg_24h(void) { s_clock_is_24h_style = true; prv_set_data(&s_data, 10323, 7500, 8000, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_kickstart__render_hr_bpm_24h(void) { #if (PLATFORM_SILK || PLATFORM_ROBERT) s_clock_is_24h_style = true; prv_set_data(&s_data, 10323, 7500, 13000, 82); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); #endif } void test_kickstart__render_hr_bpm_obstructed_24h(void) { #if (PLATFORM_SILK || PLATFORM_ROBERT) s_clock_is_24h_style = true; prv_set_data(&s_data, 10323, 7500, 13000, 82); prv_set_unobstructed_area_height(TIMELINE_PEEK_HEIGHT); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); #endif } void test_kickstart__render_PBL_43681(void) { prv_set_data(&s_data, 0, 1098, 8, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_kickstart__render_PBL_43717(void) { prv_set_data(&s_data, 7, 0, 7, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); }
prv_set_unobstructed_area_height(0)
<|repo_name|>pebble <|file_sep|>tests/fw/apps/watch/kickstart/test_kickstart.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apps/watch/kickstart/kickstart.h" #include "popups/timeline/peek.h" #include "applib/ui/window_private.h" #include "fw/graphics/util.h" #include "util/size.h" #include "clar.h" extern void prv_window_load_handler(Window *window); extern void prv_window_unload_handler(Window *window); extern void prv_set_unobstructed_area_height(int16_t height); extern void prv_set_data(KickstartData *data, int32_t current_steps, int32_t typical_steps, int32_t daily_steps_avg, int32_t current_bpm); // Fakes ///////////////////// #include "fake_pbl_std.h" #include "fake_spi_flash.h" #include "fixtures/load_test_resources.h" static bool s_clock_is_24h_style = false; bool clock_is_24h_style(void) { return s_clock_is_24h_style; } // Stubs ///////////////////// #include "stubs_analytics.h" #include "stubs_app.h" #include "stubs_app_install_manager.h" #include "stubs_app_timer.h" #include "stubs_app_window_stack.h" #include "stubs_bootbits.h" #include "stubs_click.h" #include "stubs_event_service_client.h" #include "stubs_health_service.h" #include "stubs_layer.h" #include "stubs_logging.h" #include "stubs_memory_layout.h" #include "stubs_mutex.h" #include "stubs_passert.h" #include "stubs_pbl_malloc.h" #include "stubs_pebble_process_info.h" #include "stubs_pebble_tasks.h" #include "stubs_process_manager.h" #include "stubs_prompt.h" #include "stubs_serial.h" #include "stubs_shell_prefs.h" #include "stubs_sleep.h" #include "stubs_syscalls.h" #include "stubs_task_watchdog.h" #include "stubs_text_layer_flow.h" #include "stubs_vibes.h" #include "stubs_window_manager.h" #include "stubs_window_stack.h" void tick_timer_service_subscribe(TimeUnits tick_units, TickHandler handler) {} void tick_timer_service_unsubscribe(void) {} // Setup and Teardown //////////////////////////////////// static GContext s_ctx; static FrameBuffer s_fb; static KickstartData s_data; GContext *graphics_context_get_current_context(void) { return &s_ctx; } void test_kickstart__initialize(void) { // Setup graphics context framebuffer_init(&s_fb, &(GSize) {DISP_COLS, DISP_ROWS}); framebuffer_clear(&s_fb); graphics_context_init(&s_ctx, &s_fb, GContextInitializationMode_App); s_app_state_get_graphics_context = &s_ctx; // Setup resources fake_spi_flash_init(0 /* offset */, 0x1000000 /* length */); pfs_init(false /* run filesystem check */); pfs_format(true /* write erase headers */); load_resource_fixture_in_flash(RESOURCES_FIXTURE_PATH, SYSTEM_RESOURCES_FIXTURE_NAME, false /* is_next */); resource_init(); // Reset data prv_set_data(&s_data, 0, 0, 0, 0); <|fim_suffix|>; s_clock_is_24h_style = false; // Init window window_init(&s_data.window, WINDOW_NAME("Kickstart")); window_set_user_data(&s_data.window, &s_data); window_set_window_handlers(&s_data.window, &(WindowHandlers){ .load = prv_window_load_handler, .unload = prv_window_unload_handler, }); } void test_kickstart__cleanup(void) { window_deinit(&s_data.window); } // Tests ////////////////////// void test_kickstart__render_no_data(void) { window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_kickstart__render_obstructed_area(void) { #if !PBL_ROUND prv_set_unobstructed_area_height(TIMELINE_PEEK_HEIGHT); prv_set_data(&s_data, 5543, 6500, 8000, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); #endif } void test_kickstart__render_steps_above_typical(void) { prv_set_data(&s_data, 3528, 2500, 8000, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_kickstart__render_steps_below_typical(void) { prv_set_data(&s_data, 5543, 6500, 8000, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_kickstart__render_steps_above_daily_avg(void) { prv_set_data(&s_data, 10323, 7500, 8000, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_kickstart__render_hr_bpm(void) { #if (PLATFORM_SILK || PLATFORM_ROBERT) prv_set_data(&s_data, 10323, 7500, 13000, 82); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); #endif } void test_kickstart__render_hr_bpm_obstructed(void) { #if (PLATFORM_SILK || PLATFORM_ROBERT) prv_set_data(&s_data, 10323, 7500, 13000, 82); prv_set_unobstructed_area_height(TIMELINE_PEEK_HEIGHT); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); #endif } void test_kickstart__render_steps_above_daily_avg_24h(void) { s_clock_is_24h_style = true; prv_set_data(&s_data, 10323, 7500, 8000, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_kickstart__render_hr_bpm_24h(void) { #if (PLATFORM_SILK || PLATFORM_ROBERT) s_clock_is_24h_style = true; prv_set_data(&s_data, 10323, 7500, 13000, 82); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); #endif } void test_kickstart__render_hr_bpm_obstructed_24h(void) { #if (PLATFORM_SILK || PLATFORM_ROBERT) s_clock_is_24h_style = true; prv_set_data(&s_data, 10323, 7500, 13000, 82); prv_set_unobstructed_area_height(TIMELINE_PEEK_HEIGHT); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); #endif } void test_kickstart__render_PBL_43681(void) { prv_set_data(&s_data, 0, 1098, 8, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } void test_kickstart__render_PBL_43717(void) { prv_set_data(&s_data, 7, 0, 7, 0); window_set_on_screen(&s_data.window, true, true); window_render(&s_data.window, &s_ctx); cl_check(gbitmap_pbi_eq(&s_ctx.dest_bitmap, TEST_PBI_FILE)); } <|fim_middle|>prv_set_unobstructed_area_height(0)<|endoftext|>
masked_node
argument_list
tests/fw/services/test_pfs.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string.h> #include <stdlib.h> #include "drivers/flash.h" #include "flash_region/flash_region.h" #include "services/normal/filesystem/pfs.h" #include "services/normal/filesystem/flash_translation.h" #include "system/logging.h" #include "system/passert.h" #include "util/math.h" #include "util/size.h" #include "clar.h" #include "fake_spi_flash.h" #include "fake_rtc.h" #include "stubs_analytics.h" #include "stubs_logging.h" #include "stubs_mutex.h" #include "stubs_passert.h" #include "stubs_pbl_malloc.h" #include "stubs_pebble_tasks.h" #include "stubs_print.h" #include "stubs_prompt.h" #include "stubs_serial.h" #include "stubs_sleep.h" #include "stubs_task_watchdog.h" #define PFS_SECTOR_SIZE 4096 // a - 4K file full of 1's static const char *const TEST_FILE_A_NAME = "a"; static const size_t TEST_FILE_A_SIZE = 4096; static char s_test_file_a[TEST_FILE_A_SIZE]; // b - 0K file for appending static const char *const TEST_FILE_B_NAME = "b"; static const size_t TEST_FILE_B_SIZE = 0; static const size_t TEST_FILE_B_APPEND_SIZE = 8000; static char s_test_file_b[TEST_FILE_B_APPEND_SIZE]; // c - space to perform non-append writes static const char *const TEST_FILE_C_NAME = "c"; static const size_t TEST_FILE_C_SIZE = 9001; // it's over 9000! static char s_test_file_c[TEST_FILE_C_SIZE]; static uint32_t num_pages(void) { return pfs_get_size() / PFS_SECTOR_SIZE; } void test_pfs__initialize(void) { fake_spi_flash_init(0, 0x1000000); pfs_init(false); pfs_format(true /* write erase headers */); // should have: this should be baked into an image. Perhaps with a test run // that captures a gold flash image? int fd; memset(s_test_file_a, 0, sizeof(s_test_file_a)); fd = pfs_open(TEST_FILE_A_NAME, OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof(s_test_file_a)); pfs_write(fd, (uint8_t *)s_test_file_a, sizeof(s_test_file_a)); pfs_close(fd); memset(s_test_file_b, 0, sizeof(s_test_file_b)); fd = pfs_open(TEST_FILE_B_NAME, OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof(s_test_file_b)); pfs_close(fd); fd = pfs_open(TEST_FILE_C_NAME, OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof (s_test_file_c)); for (unsigned int i = 0; i < ARRAY_LENGTH(s_test_file_c); ++i) { s_test_file_c[i] = 'c'; } pfs_write(fd, (uint8_t *)s_test_file_c, sizeof(s_test_file_c)); pfs_close(fd); } void test_pfs__cleanup(void) { fake_spi_flash_cleanup(); } void test_pfs__create(void) { char hello[] = { 'h', 'e', 'l', 'l', 'o' }; int fd_z = pfs_open("z", OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof(hello)); cl_assert(fd_z >= 0); int bytes_written = pfs_write
; cl_assert(bytes_written == sizeof(hello)); pfs_close(fd_z); } extern void test_force_garbage_collection(uint16_t start_page); extern uint16_t test_get_file_start_page(int fd); void test_pfs__garbage_collection(void) { char file_small[10]; uint16_t start_page = 0; // create a sectors worth of files for (int i = 0; i < 16; i++) { snprintf(file_small, sizeof(file_small), "file%d", i); uint8_t buf[PFS_SECTOR_SIZE * 2]; memset(&buf[0], i, sizeof(buf)); int fd = pfs_open(file_small, OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof(buf)); printf("fd=%d\n", fd); cl_assert(fd >= 0); cl_assert_equal_i(pfs_write(fd, &buf[0], sizeof(buf)), sizeof(buf)); if (i == 0) { start_page = test_get_file_start_page(fd); } if ((i % 2) != 0) { pfs_close_and_remove(fd); } else { pfs_close(fd); } } // force garbage collection test_force_garbage_collection(start_page); // now make sure the files are still there! for (int i = 0; i < 16; i+=2) { snprintf(file_small, sizeof(file_small), "file%d", i); uint8_t buf[PFS_SECTOR_SIZE * 2]; uint8_t bufcmp[PFS_SECTOR_SIZE * 2]; memset(&bufcmp[0], i, sizeof(bufcmp)); int fd = pfs_open(file_small, OP_FLAG_READ, FILE_TYPE_STATIC, sizeof(buf)); cl_assert(fd >= 0); cl_assert_equal_i(pfs_read(fd, &buf[0], sizeof(buf)), sizeof(buf)); cl_assert(memcmp(buf, bufcmp, sizeof(buf)) == 0); cl_assert_equal_i(pfs_close(fd), S_SUCCESS); } } void test_pfs__garbage_collection_when_full(void) { char file_name[10]; int num = 0; int fd; while (1) { snprintf(file_name, sizeof(file_name), "file%d", num++); fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof(file_name)); cl_assert((fd >= 0) || (fd == E_OUT_OF_STORAGE)); if (fd == E_OUT_OF_STORAGE) { break; } cl_assert_equal_i(pfs_close(fd), S_SUCCESS); } // the file system is full, lets delete a file snprintf(file_name, sizeof(file_name), "file%d", num / 2); fd = pfs_open(file_name, OP_FLAG_READ, 0, 0); cl_assert(fd >= 0); uint16_t target_start_page = test_get_file_start_page(fd); pfs_close_and_remove(fd); // lets force garbage collection on every sector test_force_garbage_collection(target_start_page); // now lets try to create a file fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof(file_name)); cl_assert_equal_i(target_start_page, test_get_file_start_page(fd)); cl_assert(fd >= 0); cl_assert_equal_i(pfs_close(fd), S_SUCCESS); } void test_pfs__open(void) { int fd = pfs_open("dne", OP_FLAG_READ, 0, 0); cl_assert(fd == E_DOES_NOT_EXIST); fd = pfs_open("dne", OP_FLAG_OVERWRITE, FILE_TYPE_STATIC, 0); cl_assert(fd == E_DOES_NOT_EXIST); char name[] = {'a'}; int fds[100]; // arbitrarily large # of FDs int i; for (i = 0; i < (sizeof(fds) - 1); i++) { fds[i] = pfs_open(name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10); name[0]++; if (fds[i] < 0) { break; } } cl_assert(fds[i] == E_OUT_OF_RESOURCES); for (int j = 0; j < i; j++) { cl_assert(pfs_close(fds[j]) == S_SUCCESS); } fd = pfs_open("newfile", OP_FLAG_WRITE, FILE_TYPE_STATIC, 10); cl_assert(fd >= 0); pfs_close(fd); int fd2 = pfs_open("newfile", OP_FLAG_READ, 0, 0); cl_assert((fd2 >= 0) && (fd == fd2)); // should have a cache hit pfs_close(fd2); fd = pfs_open("toobig", OP_FLAG_WRITE, FILE_TYPE_STATIC, 256 * 1024 * 1024); cl_assert(fd == E_OUT_OF_STORAGE); fd = pfs_open("toobig", OP_FLAG_READ, 0, 0); cl_assert(fd == E_DOES_NOT_EXIST); fd = pfs_open(NULL, OP_FLAG_READ, 0, 0); cl_assert(fd == E_INVALID_ARGUMENT); fd = pfs_open("newfile2", OP_FLAG_WRITE, FILE_TYPE_STATIC, 8000); cl_assert(fd >= 0); cl_assert(pfs_close(fd) == S_SUCCESS); } void test_pfs__page_lookup_cache(void) { // create fragmentation in the filesystem char file_small[10]; char buf_small[50]; for (int i = 0; i < num_pages(); i++) { snprintf(file_small, sizeof(file_small), "file%d", i); snprintf(buf_small, sizeof(buf_small), "This is sm
(fd_z, (uint8_t *)hello, sizeof(hello))
<|repo_name|>pebble <|file_sep|>tests/fw/services/test_pfs.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string.h> #include <stdlib.h> #include "drivers/flash.h" #include "flash_region/flash_region.h" #include "services/normal/filesystem/pfs.h" #include "services/normal/filesystem/flash_translation.h" #include "system/logging.h" #include "system/passert.h" #include "util/math.h" #include "util/size.h" #include "clar.h" #include "fake_spi_flash.h" #include "fake_rtc.h" #include "stubs_analytics.h" #include "stubs_logging.h" #include "stubs_mutex.h" #include "stubs_passert.h" #include "stubs_pbl_malloc.h" #include "stubs_pebble_tasks.h" #include "stubs_print.h" #include "stubs_prompt.h" #include "stubs_serial.h" #include "stubs_sleep.h" #include "stubs_task_watchdog.h" #define PFS_SECTOR_SIZE 4096 // a - 4K file full of 1's static const char *const TEST_FILE_A_NAME = "a"; static const size_t TEST_FILE_A_SIZE = 4096; static char s_test_file_a[TEST_FILE_A_SIZE]; // b - 0K file for appending static const char *const TEST_FILE_B_NAME = "b"; static const size_t TEST_FILE_B_SIZE = 0; static const size_t TEST_FILE_B_APPEND_SIZE = 8000; static char s_test_file_b[TEST_FILE_B_APPEND_SIZE]; // c - space to perform non-append writes static const char *const TEST_FILE_C_NAME = "c"; static const size_t TEST_FILE_C_SIZE = 9001; // it's over 9000! static char s_test_file_c[TEST_FILE_C_SIZE]; static uint32_t num_pages(void) { return pfs_get_size() / PFS_SECTOR_SIZE; } void test_pfs__initialize(void) { fake_spi_flash_init(0, 0x1000000); pfs_init(false); pfs_format(true /* write erase headers */); // should have: this should be baked into an image. Perhaps with a test run // that captures a gold flash image? int fd; memset(s_test_file_a, 0, sizeof(s_test_file_a)); fd = pfs_open(TEST_FILE_A_NAME, OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof(s_test_file_a)); pfs_write(fd, (uint8_t *)s_test_file_a, sizeof(s_test_file_a)); pfs_close(fd); memset(s_test_file_b, 0, sizeof(s_test_file_b)); fd = pfs_open(TEST_FILE_B_NAME, OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof(s_test_file_b)); pfs_close(fd); fd = pfs_open(TEST_FILE_C_NAME, OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof (s_test_file_c)); for (unsigned int i = 0; i < ARRAY_LENGTH(s_test_file_c); ++i) { s_test_file_c[i] = 'c'; } pfs_write(fd, (uint8_t *)s_test_file_c, sizeof(s_test_file_c)); pfs_close(fd); } void test_pfs__cleanup(void) { fake_spi_flash_cleanup(); } void test_pfs__create(void) { char hello[] = { 'h', 'e', 'l', 'l', 'o' }; int fd_z = pfs_open("z", OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof(hello)); cl_assert(fd_z >= 0); int bytes_written = pfs_write<|fim_suffix|>; cl_assert(bytes_written == sizeof(hello)); pfs_close(fd_z); } extern void test_force_garbage_collection(uint16_t start_page); extern uint16_t test_get_file_start_page(int fd); void test_pfs__garbage_collection(void) { char file_small[10]; uint16_t start_page = 0; // create a sectors worth of files for (int i = 0; i < 16; i++) { snprintf(file_small, sizeof(file_small), "file%d", i); uint8_t buf[PFS_SECTOR_SIZE * 2]; memset(&buf[0], i, sizeof(buf)); int fd = pfs_open(file_small, OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof(buf)); printf("fd=%d\n", fd); cl_assert(fd >= 0); cl_assert_equal_i(pfs_write(fd, &buf[0], sizeof(buf)), sizeof(buf)); if (i == 0) { start_page = test_get_file_start_page(fd); } if ((i % 2) != 0) { pfs_close_and_remove(fd); } else { pfs_close(fd); } } // force garbage collection test_force_garbage_collection(start_page); // now make sure the files are still there! for (int i = 0; i < 16; i+=2) { snprintf(file_small, sizeof(file_small), "file%d", i); uint8_t buf[PFS_SECTOR_SIZE * 2]; uint8_t bufcmp[PFS_SECTOR_SIZE * 2]; memset(&bufcmp[0], i, sizeof(bufcmp)); int fd = pfs_open(file_small, OP_FLAG_READ, FILE_TYPE_STATIC, sizeof(buf)); cl_assert(fd >= 0); cl_assert_equal_i(pfs_read(fd, &buf[0], sizeof(buf)), sizeof(buf)); cl_assert(memcmp(buf, bufcmp, sizeof(buf)) == 0); cl_assert_equal_i(pfs_close(fd), S_SUCCESS); } } void test_pfs__garbage_collection_when_full(void) { char file_name[10]; int num = 0; int fd; while (1) { snprintf(file_name, sizeof(file_name), "file%d", num++); fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof(file_name)); cl_assert((fd >= 0) || (fd == E_OUT_OF_STORAGE)); if (fd == E_OUT_OF_STORAGE) { break; } cl_assert_equal_i(pfs_close(fd), S_SUCCESS); } // the file system is full, lets delete a file snprintf(file_name, sizeof(file_name), "file%d", num / 2); fd = pfs_open(file_name, OP_FLAG_READ, 0, 0); cl_assert(fd >= 0); uint16_t target_start_page = test_get_file_start_page(fd); pfs_close_and_remove(fd); // lets force garbage collection on every sector test_force_garbage_collection(target_start_page); // now lets try to create a file fd = pfs_open(file_name, OP_FLAG_WRITE, FILE_TYPE_STATIC, sizeof(file_name)); cl_assert_equal_i(target_start_page, test_get_file_start_page(fd)); cl_assert(fd >= 0); cl_assert_equal_i(pfs_close(fd), S_SUCCESS); } void test_pfs__open(void) { int fd = pfs_open("dne", OP_FLAG_READ, 0, 0); cl_assert(fd == E_DOES_NOT_EXIST); fd = pfs_open("dne", OP_FLAG_OVERWRITE, FILE_TYPE_STATIC, 0); cl_assert(fd == E_DOES_NOT_EXIST); char name[] = {'a'}; int fds[100]; // arbitrarily large # of FDs int i; for (i = 0; i < (sizeof(fds) - 1); i++) { fds[i] = pfs_open(name, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10); name[0]++; if (fds[i] < 0) { break; } } cl_assert(fds[i] == E_OUT_OF_RESOURCES); for (int j = 0; j < i; j++) { cl_assert(pfs_close(fds[j]) == S_SUCCESS); } fd = pfs_open("newfile", OP_FLAG_WRITE, FILE_TYPE_STATIC, 10); cl_assert(fd >= 0); pfs_close(fd); int fd2 = pfs_open("newfile", OP_FLAG_READ, 0, 0); cl_assert((fd2 >= 0) && (fd == fd2)); // should have a cache hit pfs_close(fd2); fd = pfs_open("toobig", OP_FLAG_WRITE, FILE_TYPE_STATIC, 256 * 1024 * 1024); cl_assert(fd == E_OUT_OF_STORAGE); fd = pfs_open("toobig", OP_FLAG_READ, 0, 0); cl_assert(fd == E_DOES_NOT_EXIST); fd = pfs_open(NULL, OP_FLAG_READ, 0, 0); cl_assert(fd == E_INVALID_ARGUMENT); fd = pfs_open("newfile2", OP_FLAG_WRITE, FILE_TYPE_STATIC, 8000); cl_assert(fd >= 0); cl_assert(pfs_close(fd) == S_SUCCESS); } void test_pfs__page_lookup_cache(void) { // create fragmentation in the filesystem char file_small[10]; char buf_small[50]; for (int i = 0; i < num_pages(); i++) { snprintf(file_small, sizeof(file_small), "file%d", i); snprintf(buf_small, sizeof(buf_small), "This is sm<|fim_middle|>(fd_z, (uint8_t *)hello, sizeof(hello))<|endoftext|>
masked_node
call_expression
src/fw/drivers/flash/micron_n25q/cd_flash_driver.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <inttypes.h> #include "drivers/flash.h" #include "drivers/flash/micron_n25q/flash_private.h" #include "drivers/watchdog.h" #include "flash_region/flash_region.h" #include "kernel/util/delay.h" #include "util/math.h" #include "kernel/core_dump_private.h" //! We have our own flash driver for coredump support because it must not use //! any FreeRTOS constructs & we want to keep it as simple as possible. In //! addition we want the flexibility to be able to reset the flash driver to //! get it into a working state static void prv_flash_start_cmd(void) { GPIO_ResetBits(FLASH_GPIO, FLASH_PIN_SCS); } static void prv_flash_end_cmd(void) { GPIO_SetBits(FLASH_GPIO, FLASH_PIN_SCS); // 50ns required between SCS going high and low again, so just delay here to be safe delay_us(1); } static uint8_t prv_flash_send_and_receive_byte(uint8_t byte) { // Ensure that there are no other write operations in progress while (SPI_I2S_GetFlagStatus(FLASH_SPI, SPI_I2S_FLAG_TXE) == RESET) { continue; } // Send the byte on the SPI bus SPI_I2S_SendData(FLASH_SPI, byte); // Wait for the response byte to be received while (SPI_I2S_GetFlagStatus(FLASH_SPI, SPI_I2S_FLAG_RXNE) == RESET) { continue; } // Return the byte return SPI_I2S_ReceiveData(FLASH_SPI); } static uint8_t prv_flash_read_next_byte(void) { uint8_t result = prv_flash_send_and_receive_byte(FLASH_CMD_DUMMY); return result; } static void prv_flash_wait_for_write_bounded(volatile int cycles_to_wait) { prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_READ_STATUS_REG); uint8_t status_register = 0; do { if (cycles_to_wait-- < 1) { break; } status_register = prv_flash_read_next_byte(); } while (status_register & 0x1); prv_flash_end_cmd(); } // Init the flash hardware void cd_flash_init(void) { // Enable the SPI clock RCC_APB2PeriphClockCmd(FLASH_SPI_CLOCK, ENABLE); // Enable the GPIO clock uint8_t idx = ((((uint32_t)FLASH_GPIO) - AHB1PERIPH_BASE) / 0x0400); SET_BIT(RCC->AHB1ENR, (0x1 << idx)); // Init the flash hardware flash_hw_init(); // Make sure we are not in deep sleep prv_flash_start_cmd();
; prv_flash_end_cmd(); // See if we can successfully access the flash // TODO: Will we successfully recover if the flash HW was left midstream in a command from // before? prv_flash_wait_for_write_bounded(64000000); prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_READ_ID); uint32_t manufacturer = prv_flash_read_next_byte(); uint32_t type = prv_flash_read_next_byte(); uint32_t capacity = prv_flash_read_next_byte(); prv_flash_end_cmd(); // If we can't ready the flash info correctly, bail CD_ASSERTN(manufacturer == 0x20 && type == 0xbb && (capacity >= 0x16)); } static void prv_flash_write_enable(void) { prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_WRITE_ENABLE); prv_flash_end_cmd(); } static void prv_flash_send_24b_address(uint32_t start_addr) { // Ensure the high bits are not set. prv_flash_send_and_receive_byte((start_addr & 0xFF0000) >> 16); prv_flash_send_and_receive_byte((start_addr & 0x00FF00) >> 8); prv_flash_send_and_receive_byte((start_addr & 0x0000FF)); } static void prv_flash_wait_for_write(void) { prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_READ_STATUS_REG); uint8_t status_register = 0; do { status_register = prv_flash_read_next_byte(); } while (status_register & 0x1); prv_flash_end_cmd(); } static void prv_flash_write_page(const uint8_t* buffer, uint32_t start_addr, uint16_t buffer_size) { // Ensure that we're not trying to write more data than a single page (256 bytes) CD_ASSERTN(buffer_size <= FLASH_PAGE_SIZE); CD_ASSERTN(buffer_size); // Writing a zero-length buffer is a no-op. if (buffer_size < 1) { return; } prv_flash_write_enable(); prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_PAGE_PROGRAM); prv_flash_send_24b_address(start_addr); while (buffer_size--) { prv_flash_send_and_receive_byte(*buffer); buffer++; } prv_flash_end_cmd(); prv_flash_wait_for_write(); } void cd_flash_read_bytes(void* buffer_ptr, uint32_t start_addr, uint32_t buffer_size) { uint8_t* buffer = buffer_ptr; prv_flash_wait_for_write(); prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_READ); prv_flash_send_24b_address(start_addr); while (buffer_size--) { *buffer = prv_flash_read_next_byte(); buffer++; } prv_flash_end_cmd(); } uint32_t cd_flash_write_bytes(const void* buffer_ptr, uint32_t start_addr, uint32_t buffer_size) { CD_ASSERTN((start_addr + buffer_size <= CORE_DUMP_FLASH_END) && (int)start_addr >= CORE_DUMP_FLASH_START); const uint8_t* buffer = buffer_ptr; const uint32_t total_bytes = buffer_size; uint32_t first_page_available_bytes = FLASH_PAGE_SIZE - (start_addr % FLASH_PAGE_SIZE); uint32_t bytes_to_write = MIN(buffer_size, first_page_available_bytes); while (bytes_to_write) { prv_flash_write_page(buffer, start_addr, bytes_to_write); start_addr += bytes_to_write; buffer += bytes_to_write; buffer_size -= bytes_to_write; bytes_to_write = MIN(buffer_size, FLASH_PAGE_SIZE); } watchdog_feed(); return total_bytes; } static void prv_flash_erase_sector(uint32_t sector_addr) { prv_flash_write_enable(); prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_ERASE_SECTOR); prv_flash_send_24b_address(sector_addr); prv_flash_end_cmd(); prv_flash_wait_for_write(); } static void prv_flash_erase_subsector(uint32_t sector_addr) { prv_flash_write_enable(); prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_ERASE_SUBSECTOR); prv_flash_send_24b_address(sector_addr); prv_flash_end_cmd(); prv_flash_wait_for_write(); } // Erase a region comprised of 1 or more sub-sectors. This will erase sectors at a time if // the address and size allow. void cd_flash_erase_region(uint32_t start_addr, uint32_t total_bytes) { CD_ASSERTN(((start_addr & SUBSECTOR_ADDR_MASK) == start_addr) && ((total_bytes & SUBSECTOR_ADDR_MASK) == total_bytes)); while (total_bytes > 0) { if (((start_addr & SECTOR_ADDR_M
prv_flash_send_and_receive_byte(FLASH_CMD_WAKE)
<|repo_name|>pebble <|file_sep|>src/fw/drivers/flash/micron_n25q/cd_flash_driver.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <inttypes.h> #include "drivers/flash.h" #include "drivers/flash/micron_n25q/flash_private.h" #include "drivers/watchdog.h" #include "flash_region/flash_region.h" #include "kernel/util/delay.h" #include "util/math.h" #include "kernel/core_dump_private.h" //! We have our own flash driver for coredump support because it must not use //! any FreeRTOS constructs & we want to keep it as simple as possible. In //! addition we want the flexibility to be able to reset the flash driver to //! get it into a working state static void prv_flash_start_cmd(void) { GPIO_ResetBits(FLASH_GPIO, FLASH_PIN_SCS); } static void prv_flash_end_cmd(void) { GPIO_SetBits(FLASH_GPIO, FLASH_PIN_SCS); // 50ns required between SCS going high and low again, so just delay here to be safe delay_us(1); } static uint8_t prv_flash_send_and_receive_byte(uint8_t byte) { // Ensure that there are no other write operations in progress while (SPI_I2S_GetFlagStatus(FLASH_SPI, SPI_I2S_FLAG_TXE) == RESET) { continue; } // Send the byte on the SPI bus SPI_I2S_SendData(FLASH_SPI, byte); // Wait for the response byte to be received while (SPI_I2S_GetFlagStatus(FLASH_SPI, SPI_I2S_FLAG_RXNE) == RESET) { continue; } // Return the byte return SPI_I2S_ReceiveData(FLASH_SPI); } static uint8_t prv_flash_read_next_byte(void) { uint8_t result = prv_flash_send_and_receive_byte(FLASH_CMD_DUMMY); return result; } static void prv_flash_wait_for_write_bounded(volatile int cycles_to_wait) { prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_READ_STATUS_REG); uint8_t status_register = 0; do { if (cycles_to_wait-- < 1) { break; } status_register = prv_flash_read_next_byte(); } while (status_register & 0x1); prv_flash_end_cmd(); } // Init the flash hardware void cd_flash_init(void) { // Enable the SPI clock RCC_APB2PeriphClockCmd(FLASH_SPI_CLOCK, ENABLE); // Enable the GPIO clock uint8_t idx = ((((uint32_t)FLASH_GPIO) - AHB1PERIPH_BASE) / 0x0400); SET_BIT(RCC->AHB1ENR, (0x1 << idx)); // Init the flash hardware flash_hw_init(); // Make sure we are not in deep sleep prv_flash_start_cmd(); <|fim_suffix|>; prv_flash_end_cmd(); // See if we can successfully access the flash // TODO: Will we successfully recover if the flash HW was left midstream in a command from // before? prv_flash_wait_for_write_bounded(64000000); prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_READ_ID); uint32_t manufacturer = prv_flash_read_next_byte(); uint32_t type = prv_flash_read_next_byte(); uint32_t capacity = prv_flash_read_next_byte(); prv_flash_end_cmd(); // If we can't ready the flash info correctly, bail CD_ASSERTN(manufacturer == 0x20 && type == 0xbb && (capacity >= 0x16)); } static void prv_flash_write_enable(void) { prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_WRITE_ENABLE); prv_flash_end_cmd(); } static void prv_flash_send_24b_address(uint32_t start_addr) { // Ensure the high bits are not set. prv_flash_send_and_receive_byte((start_addr & 0xFF0000) >> 16); prv_flash_send_and_receive_byte((start_addr & 0x00FF00) >> 8); prv_flash_send_and_receive_byte((start_addr & 0x0000FF)); } static void prv_flash_wait_for_write(void) { prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_READ_STATUS_REG); uint8_t status_register = 0; do { status_register = prv_flash_read_next_byte(); } while (status_register & 0x1); prv_flash_end_cmd(); } static void prv_flash_write_page(const uint8_t* buffer, uint32_t start_addr, uint16_t buffer_size) { // Ensure that we're not trying to write more data than a single page (256 bytes) CD_ASSERTN(buffer_size <= FLASH_PAGE_SIZE); CD_ASSERTN(buffer_size); // Writing a zero-length buffer is a no-op. if (buffer_size < 1) { return; } prv_flash_write_enable(); prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_PAGE_PROGRAM); prv_flash_send_24b_address(start_addr); while (buffer_size--) { prv_flash_send_and_receive_byte(*buffer); buffer++; } prv_flash_end_cmd(); prv_flash_wait_for_write(); } void cd_flash_read_bytes(void* buffer_ptr, uint32_t start_addr, uint32_t buffer_size) { uint8_t* buffer = buffer_ptr; prv_flash_wait_for_write(); prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_READ); prv_flash_send_24b_address(start_addr); while (buffer_size--) { *buffer = prv_flash_read_next_byte(); buffer++; } prv_flash_end_cmd(); } uint32_t cd_flash_write_bytes(const void* buffer_ptr, uint32_t start_addr, uint32_t buffer_size) { CD_ASSERTN((start_addr + buffer_size <= CORE_DUMP_FLASH_END) && (int)start_addr >= CORE_DUMP_FLASH_START); const uint8_t* buffer = buffer_ptr; const uint32_t total_bytes = buffer_size; uint32_t first_page_available_bytes = FLASH_PAGE_SIZE - (start_addr % FLASH_PAGE_SIZE); uint32_t bytes_to_write = MIN(buffer_size, first_page_available_bytes); while (bytes_to_write) { prv_flash_write_page(buffer, start_addr, bytes_to_write); start_addr += bytes_to_write; buffer += bytes_to_write; buffer_size -= bytes_to_write; bytes_to_write = MIN(buffer_size, FLASH_PAGE_SIZE); } watchdog_feed(); return total_bytes; } static void prv_flash_erase_sector(uint32_t sector_addr) { prv_flash_write_enable(); prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_ERASE_SECTOR); prv_flash_send_24b_address(sector_addr); prv_flash_end_cmd(); prv_flash_wait_for_write(); } static void prv_flash_erase_subsector(uint32_t sector_addr) { prv_flash_write_enable(); prv_flash_start_cmd(); prv_flash_send_and_receive_byte(FLASH_CMD_ERASE_SUBSECTOR); prv_flash_send_24b_address(sector_addr); prv_flash_end_cmd(); prv_flash_wait_for_write(); } // Erase a region comprised of 1 or more sub-sectors. This will erase sectors at a time if // the address and size allow. void cd_flash_erase_region(uint32_t start_addr, uint32_t total_bytes) { CD_ASSERTN(((start_addr & SUBSECTOR_ADDR_MASK) == start_addr) && ((total_bytes & SUBSECTOR_ADDR_MASK) == total_bytes)); while (total_bytes > 0) { if (((start_addr & SECTOR_ADDR_M<|fim_middle|>prv_flash_send_and_receive_byte(FLASH_CMD_WAKE)<|endoftext|>
masked_node
call_expression
src/fw/applib/app_recognizers.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "app_recognizers.h" #include "process_state/app_state/app_state.h" void app_recognizers_attach_recognizer(Recognizer *recognizer) { recognizer_add_to_list(recognizer, app_state_get_recognizer_list()); } void app_recognizers_detach_recognizer(Recognizer *recognizer) { recognizer_remove_from_list(recognizer,
); }
app_state_get_recognizer_list()
<|repo_name|>pebble <|file_sep|>src/fw/applib/app_recognizers.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "app_recognizers.h" #include "process_state/app_state/app_state.h" void app_recognizers_attach_recognizer(Recognizer *recognizer) { recognizer_add_to_list(recognizer, app_state_get_recognizer_list()); } void app_recognizers_detach_recognizer(Recognizer *recognizer) { recognizer_remove_from_list(recognizer, <|fim_suffix|>); } <|fim_middle|>app_state_get_recognizer_list()<|endoftext|>
masked_node
argument_list
tests/fw/services/test_app_cache.c
.id = 15, .priority = 19, .size = 117885 }, // priority rank 11 { .id = 16, .priority = 42, .size = 167427 }, // priority rank 31 { .id = 17, .priority = 1, .size = 22644 }, // priority rank 2 { .id = 18, .priority = 30, .size = 33202 }, // priority rank 22 { .id = 19, .priority = 25, .size = 151434 }, // priority rank 18 { .id = 20, .priority = 33, .size = 102321 }, // priority rank 24 { .id = 21, .priority = 19, .size = 223352 }, // priority rank 9 { .id = 22, .priority = 36, .size = 133221 }, // priority rank 25 { .id = 23, .priority = 51, .size = 169128 }, // priority rank 39 { .id = 24, .priority = 22, .size = 103055 }, // priority rank 14 { .id = 25, .priority = 44, .size = 182304 }, // priority rank 33 { .id = 26, .priority = 2, .size = 177430 }, // priority rank 3 { .id = 27, .priority = 5, .size = 248430 }, // priority rank 4 { .id = 28, .priority = 44, .size = 168622 }, // priority rank 34 { .id = 29, .priority = 6, .size = 192857 }, // priority rank 5 { .id = 30, .priority = 19, .size = 183331 }, // priority rank 10 { .id = 31, .priority = 61, .size = 111155 }, // priority rank 50 { .id = 32, .priority = 42, .size = 211695 }, // priority rank 30 { .id = 33, .priority = 49, .size = 35653 }, // priority rank 38 { .id = 34, .priority = 57, .size = 11541 }, // priority rank 44 { .id = 35, .priority = 40, .size = 49368 }, // priority rank 29 { .id = 36, .priority = 25, .size = 230982 }, // priority rank 17 { .id = 37, .priority = 32, .size = 185018 }, // priority rank 23 { .id = 38, .priority = 39, .size = 163897 }, // priority rank 27 { .id = 39, .priority = 24, .size = 233217 }, // priority rank 16 { .id = 40, .priority = 8, .size = 23717 }, // priority rank 6 { .id = 41, .priority = 61, .size = 266668 }, // priority rank 49 { .id = 42, .priority = 58, .size = 61228 }, // priority rank 46 { .id = 43, .priority = 12, .size = 23513 }, // priority rank 7 { .id = 44, .priority = 60, .size = 267049 }, // priority rank 47 { .id = 45, .priority = 52, .size = 240086 }, // priority rank 40 { .id = 46, .priority = 14, .size = 194481 }, // priority rank 8 { .id = 47, .priority = 27, .size = 42163 }, // priority rank 19 { .id = 48, .priority = 56, .size = 72854 }, // priority rank 42 { .id = 49, .priority = 49, .size = 217548 }, // priority rank 37 { .id = 50, .priority = 1, .size = 207357 }, // priority rank 1 }; extern uint32_t app_cache_get_size(void); void prv_load_lotta_apps(void) { for (int i = 0; i < 50; i++) { // time is the basis of the priority. Set the time so we know what priority. rtc_set_time(t_data[i].priority); cl_assert_equal_i(S_SUCCESS, app_cache_add_entry(t_data[i].id, t_data[i].size)); cl_assert_equal_i(S_SUCCESS, app_cache_app_launched(t_data[i].id)); // increment time so everything won't happen in the same second } for (int i = 0; i < 50; i++) { cl_assert_equal_b(true, app_cache_entry_exists(t_data[i].id)); } cl_assert_equal_i(SIZE_SUM, app_cache_get_size()); } void prv_cleanup(void) { app_cache_flush(); prv_load_lotta_apps(); } void test_app_cache__free_up_space_lots_apps(void) { uint32_t to_free; uint32_t before_size; uint32_t after_size; // test random number prv_cleanup(); to_free = 150000; before_size = app_cache_get_size(); cl_assert(before_size >= to_free); cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert(after_size <= (before_size - to_free)); // test lowest priority's size prv_cleanup(); to_free = 207357; before_size = app_cache_get_size(); cl_assert(before_size >= to_free); cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert_equal_i(after_size, (before_size - to_free)); // test lowest priority's size prv_cleanup(); to_free = 1; // should remove 207357 before_size = app_cache_get_size(); cl_assert
; cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert_equal_i(after_size, (before_size - 207357)); // test two lowest priority's size prv_cleanup(); to_free = (207357 + 22644); before_size = app_cache_get_size(); cl_assert(before_size >= to_free); cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert_equal_i(after_size, (before_size - to_free)); // test removing all binaries prv_cleanup(); to_free = SIZE_SUM; before_size = app_cache_get_size(); cl_assert(before_size >= to_free); cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert_equal_i(after_size, 0); // test removing 0 bytes prv_cleanup(); to_free = 0; before_size = app_cache_get_size(); cl_assert(before_size >= to_free); cl_assert_equal_i(E_INVALID_ARGUMENT, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert_equal_i(after_size, before_size); // test removing all and more bytes prv_cleanup(); to_free = SIZE_SUM + 1; before_size = app_cache_get_size(); cl_assert(before_size < to_free); cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert_equal_i(after_size, 0); } static bool prv_file_for_id_exists(AppInstallId id) { char buffer[30]; itoa_int(id, buffer, 10); int fd = pfs_open(buffer, OP_FLAG_READ, FILE_TYPE_STATIC, 0); if (fd < 0) { return false; } pfs_close(fd); return true; } static void prv_create_file_for_id(AppInstallId id) { char buffer[30]; itoa_int(id, buffer, 10); int fd = pfs_open(buffer, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10); pfs_close(fd); } void test_app_cache__delete_binaries_for_id_with_no_entry(void) { // confirm binaries get created prv_create_file_for_id(17); cl_assert_equal_b(true, prv_file_for_id_exists(17)); // confirm binaries are deleted app_cache_remove_entry(17); cl_assert_equal_b(false, prv_file_for_id_exists(17)); } void test_app_cache__free_up_space_save_defaults(void) { uint32_t to_free; uint32_t before_size; uint32_t after_size; // lets save ids 17, 25, 42, and 47 because they are my favorite numbers uint32_t after_free = t_data[16].size + t_data[24].size + t_data[41].size + t_data[46].size; s_test_id_ql_up = 17; s_test_id_ql_down = 25; s_test_id_watchface = 42; s_test_id_worker = 47; // test removing all and more bytes prv_cleanup(); to_free = SIZE_SUM - after_free; before_size = app_cache_get_size(); PBL_LOG(LOG_LEVEL_DEBUG, "%d %d %d", to_free, after_free, before_size); cl_assert(before_size >= to_free); cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert(after_size == (before_size - to_free)); } struct file_description { const char *name; size_t size; }; static struct file_description descriptions[] = { // this first set of files match some I found on my snowy bb2 {"gap_bonding_db", 8102}, {"pmap", 5632}, {"pindb", 57095}, {"appdb", 32603}, {"reminderdb", 57090}, {"appcache", 8108}, {"alarms", 8110}, {"notifpref", 8107}, {"activity", 24436}, {"insights", 8108}, {"shellpref", 8107}, {"dls_storage_33", 4096}, {"dls_storage_122", 4096}, {"dls_storage_84", 4096}, {"dls_storage_71", 4096}, {"dls_storage_107", 4096}, {"dls_storage_176", 12555}, {"dls_storage_161", 4096}, {"dls_storage_110", 4096}, {"dls_storage_142", 4096}, {"dls_storage_197", 4096}, {"dls_storage_218", 4096}, {"dls_storage_145", 4096}, {"app_comm", 8108}, {"wakeup", 16274}, {"notifstr", 30720}, {"dls_storage_238", 4096}, {"dls_storage_116", 4096}, {"dls_storage_
(before_size >= to_free)
<|repo_name|>pebble <|file_sep|>tests/fw/services/test_app_cache.c <|fim_prefix|>.id = 15, .priority = 19, .size = 117885 }, // priority rank 11 { .id = 16, .priority = 42, .size = 167427 }, // priority rank 31 { .id = 17, .priority = 1, .size = 22644 }, // priority rank 2 { .id = 18, .priority = 30, .size = 33202 }, // priority rank 22 { .id = 19, .priority = 25, .size = 151434 }, // priority rank 18 { .id = 20, .priority = 33, .size = 102321 }, // priority rank 24 { .id = 21, .priority = 19, .size = 223352 }, // priority rank 9 { .id = 22, .priority = 36, .size = 133221 }, // priority rank 25 { .id = 23, .priority = 51, .size = 169128 }, // priority rank 39 { .id = 24, .priority = 22, .size = 103055 }, // priority rank 14 { .id = 25, .priority = 44, .size = 182304 }, // priority rank 33 { .id = 26, .priority = 2, .size = 177430 }, // priority rank 3 { .id = 27, .priority = 5, .size = 248430 }, // priority rank 4 { .id = 28, .priority = 44, .size = 168622 }, // priority rank 34 { .id = 29, .priority = 6, .size = 192857 }, // priority rank 5 { .id = 30, .priority = 19, .size = 183331 }, // priority rank 10 { .id = 31, .priority = 61, .size = 111155 }, // priority rank 50 { .id = 32, .priority = 42, .size = 211695 }, // priority rank 30 { .id = 33, .priority = 49, .size = 35653 }, // priority rank 38 { .id = 34, .priority = 57, .size = 11541 }, // priority rank 44 { .id = 35, .priority = 40, .size = 49368 }, // priority rank 29 { .id = 36, .priority = 25, .size = 230982 }, // priority rank 17 { .id = 37, .priority = 32, .size = 185018 }, // priority rank 23 { .id = 38, .priority = 39, .size = 163897 }, // priority rank 27 { .id = 39, .priority = 24, .size = 233217 }, // priority rank 16 { .id = 40, .priority = 8, .size = 23717 }, // priority rank 6 { .id = 41, .priority = 61, .size = 266668 }, // priority rank 49 { .id = 42, .priority = 58, .size = 61228 }, // priority rank 46 { .id = 43, .priority = 12, .size = 23513 }, // priority rank 7 { .id = 44, .priority = 60, .size = 267049 }, // priority rank 47 { .id = 45, .priority = 52, .size = 240086 }, // priority rank 40 { .id = 46, .priority = 14, .size = 194481 }, // priority rank 8 { .id = 47, .priority = 27, .size = 42163 }, // priority rank 19 { .id = 48, .priority = 56, .size = 72854 }, // priority rank 42 { .id = 49, .priority = 49, .size = 217548 }, // priority rank 37 { .id = 50, .priority = 1, .size = 207357 }, // priority rank 1 }; extern uint32_t app_cache_get_size(void); void prv_load_lotta_apps(void) { for (int i = 0; i < 50; i++) { // time is the basis of the priority. Set the time so we know what priority. rtc_set_time(t_data[i].priority); cl_assert_equal_i(S_SUCCESS, app_cache_add_entry(t_data[i].id, t_data[i].size)); cl_assert_equal_i(S_SUCCESS, app_cache_app_launched(t_data[i].id)); // increment time so everything won't happen in the same second } for (int i = 0; i < 50; i++) { cl_assert_equal_b(true, app_cache_entry_exists(t_data[i].id)); } cl_assert_equal_i(SIZE_SUM, app_cache_get_size()); } void prv_cleanup(void) { app_cache_flush(); prv_load_lotta_apps(); } void test_app_cache__free_up_space_lots_apps(void) { uint32_t to_free; uint32_t before_size; uint32_t after_size; // test random number prv_cleanup(); to_free = 150000; before_size = app_cache_get_size(); cl_assert(before_size >= to_free); cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert(after_size <= (before_size - to_free)); // test lowest priority's size prv_cleanup(); to_free = 207357; before_size = app_cache_get_size(); cl_assert(before_size >= to_free); cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert_equal_i(after_size, (before_size - to_free)); // test lowest priority's size prv_cleanup(); to_free = 1; // should remove 207357 before_size = app_cache_get_size(); cl_assert<|fim_suffix|>; cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert_equal_i(after_size, (before_size - 207357)); // test two lowest priority's size prv_cleanup(); to_free = (207357 + 22644); before_size = app_cache_get_size(); cl_assert(before_size >= to_free); cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert_equal_i(after_size, (before_size - to_free)); // test removing all binaries prv_cleanup(); to_free = SIZE_SUM; before_size = app_cache_get_size(); cl_assert(before_size >= to_free); cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert_equal_i(after_size, 0); // test removing 0 bytes prv_cleanup(); to_free = 0; before_size = app_cache_get_size(); cl_assert(before_size >= to_free); cl_assert_equal_i(E_INVALID_ARGUMENT, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert_equal_i(after_size, before_size); // test removing all and more bytes prv_cleanup(); to_free = SIZE_SUM + 1; before_size = app_cache_get_size(); cl_assert(before_size < to_free); cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert_equal_i(after_size, 0); } static bool prv_file_for_id_exists(AppInstallId id) { char buffer[30]; itoa_int(id, buffer, 10); int fd = pfs_open(buffer, OP_FLAG_READ, FILE_TYPE_STATIC, 0); if (fd < 0) { return false; } pfs_close(fd); return true; } static void prv_create_file_for_id(AppInstallId id) { char buffer[30]; itoa_int(id, buffer, 10); int fd = pfs_open(buffer, OP_FLAG_WRITE, FILE_TYPE_STATIC, 10); pfs_close(fd); } void test_app_cache__delete_binaries_for_id_with_no_entry(void) { // confirm binaries get created prv_create_file_for_id(17); cl_assert_equal_b(true, prv_file_for_id_exists(17)); // confirm binaries are deleted app_cache_remove_entry(17); cl_assert_equal_b(false, prv_file_for_id_exists(17)); } void test_app_cache__free_up_space_save_defaults(void) { uint32_t to_free; uint32_t before_size; uint32_t after_size; // lets save ids 17, 25, 42, and 47 because they are my favorite numbers uint32_t after_free = t_data[16].size + t_data[24].size + t_data[41].size + t_data[46].size; s_test_id_ql_up = 17; s_test_id_ql_down = 25; s_test_id_watchface = 42; s_test_id_worker = 47; // test removing all and more bytes prv_cleanup(); to_free = SIZE_SUM - after_free; before_size = app_cache_get_size(); PBL_LOG(LOG_LEVEL_DEBUG, "%d %d %d", to_free, after_free, before_size); cl_assert(before_size >= to_free); cl_assert_equal_i(S_SUCCESS, app_cache_free_up_space(to_free)); fake_system_task_callbacks_invoke_pending(); after_size = app_cache_get_size(); cl_assert(after_size == (before_size - to_free)); } struct file_description { const char *name; size_t size; }; static struct file_description descriptions[] = { // this first set of files match some I found on my snowy bb2 {"gap_bonding_db", 8102}, {"pmap", 5632}, {"pindb", 57095}, {"appdb", 32603}, {"reminderdb", 57090}, {"appcache", 8108}, {"alarms", 8110}, {"notifpref", 8107}, {"activity", 24436}, {"insights", 8108}, {"shellpref", 8107}, {"dls_storage_33", 4096}, {"dls_storage_122", 4096}, {"dls_storage_84", 4096}, {"dls_storage_71", 4096}, {"dls_storage_107", 4096}, {"dls_storage_176", 12555}, {"dls_storage_161", 4096}, {"dls_storage_110", 4096}, {"dls_storage_142", 4096}, {"dls_storage_197", 4096}, {"dls_storage_218", 4096}, {"dls_storage_145", 4096}, {"app_comm", 8108}, {"wakeup", 16274}, {"notifstr", 30720}, {"dls_storage_238", 4096}, {"dls_storage_116", 4096}, {"dls_storage_<|fim_middle|>(before_size >= to_free)<|endoftext|>
masked_node
argument_list
tests/fw/services/notifications/test_nexmo.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "clar.h" #include "services/normal/notifications/ancs/nexmo.h" #include "services/normal/notifications/ancs/ancs_notifications_util.h" #include "services/normal/timeline/attributes_actions.h" // Stubs //////////////////////////////////////////////////////////////// #include "stubs_logging.h" #include "stubs_passert.h" #include "stubs_pbl_malloc.h" // Fakes //////////////////////////////////////////////////////////////// extern const char *NEXMO_REAUTH_STRING; static AttributeList *s_expected_attributes = NULL; static TimelineItemActionGroup *s_expected_actions = NULL; static bool s_performed_store = false; status_t ios_notif_pref_db_store_prefs(const uint8_t *app_id, int length, AttributeList *attr_list, TimelineItemActionGroup *action_group) { const int buf_size = 256; uint8_t buf1[buf_size]; uint8_t buf2[buf_size]; attributes_actions_serialize_payload(attr_list, action_group, buf1, buf_size); attributes_actions_serialize_payload(s_expected_attributes, s_expected_actions, buf2, buf_size); cl_assert_equal_m(buf1, buf2, attributes_actions_get_serialized_payload_size(s_expected_attributes, s_expected_actions)); s_performed_store = true; return S_SUCCESS; } static uint32_t s_expected_uid = 0; static bool s_performed_dismiss = false; void ancs_perform_action(uint32_t notification_uid, uint8_t action_id) { cl_assert_equal_i(notification_uid, s_expected_uid); cl_assert_equal_i(action_id, ActionIDNegative); s_performed_dismiss = true; } void test_nexmo__initialize(void) { s_expected_attributes = NULL; s_expected_actions = NULL; s_performed_store = false; s_expected_uid = INVALID_UID; s_performed_dismiss = false; } void test_nexmo__cleanup(void) { } void test_nexmo__is_reuath_sms(void) { uint8_t expected_app_id_buf[128]; ANCSAttribute *expected_app_id = (ANCSAttribute *)&expected_app_id_buf; expected_app_id->length = strlen(IOS_SMS_APP_ID); memcpy(expected_app_id->value, IOS_SMS_APP_ID, strlen(IOS_SMS_APP_ID)); char valid_message[128]; strcpy(valid_message, "possible preamble "); strcat(valid_message, NEXMO_REAUTH_STRING); strcat(valid_message, " possible postamble"); uint8_t expected_message_buf[128]; ANCSAttribute *expected_message = (ANCSAttribute *)&expected_message_buf; expected_message->length = strlen(valid_message); memcpy(expected_message->value, valid_message, strlen(valid_message)); uint8_t bad_app_id_buf[128]; ANCSAttribute *bad_app_id = (ANCSAttribute *)&bad_app_id_buf; bad_app_id->length = strlen(IOS_MAIL_APP_ID); memcpy(bad_app_id->value, IOS_MAIL_APP_ID, strlen(IOS_MAIL_APP_ID)); const char *bad_string = "Phil was here"; uint8_t bad_message_buf[128]; ANCSAttribute *bad_message = (ANCSAttribute *)&bad_message_buf; bad_message->length = strlen(bad_string); memcpy(bad_message->value, bad_string, strlen(bad_string)); cl_assert
; cl_assert(!nexmo_is_reauth_sms(bad_app_id, expected_message)); cl_assert(!nexmo_is_reauth_sms(expected_app_id, bad_message)); cl_assert(!nexmo_is_reauth_sms(bad_app_id, bad_message)); } void test_nexmo__handle_reuath_sms(void) { // UID const uint32_t uid = 42; s_expected_uid = uid; // App ID uint8_t app_id_buf[128]; ANCSAttribute *app_id = (ANCSAttribute *)&app_id_buf; app_id->length = strlen(IOS_SMS_APP_ID); memcpy(app_id->value, IOS_SMS_APP_ID, strlen(IOS_SMS_APP_ID)); // Message char valid_message[128]; strcpy(valid_message, "possible preamble "); strcat(valid_message, NEXMO_REAUTH_STRING); strcat(valid_message, " possible postamble"); uint8_t message_buf[128]; ANCSAttribute *message = (ANCSAttribute *)&message_buf; message->length = strlen(valid_message); memcpy(message->value, valid_message, strlen(valid_message)); // Existing prefs iOSNotifPrefs existing_prefs = { .attr_list = { .num_attributes = 3, .attributes = (Attribute[]) { { .id = AttributeIdTitle, .cstring = "Title" }, { .id = AttributeIdBody, .cstring = "Body" }, { .id = AttributeIdAppName, .cstring = "Awesome" }, }, }, }; // Make sure that the prefs we store are the existing ones + the reauth msg AttributeList expected_attr_list = { .num_attributes = 4, .attributes = (Attribute[]) { { .id = AttributeIdTitle, .cstring = "Title" }, { .id = AttributeIdBody, .cstring = "Body" }, { .id = AttributeIdAppName, .cstring = "Awesome" }, { .id = AttributeIdAuthCode, .cstring = valid_message }, }, }; s_expected_attributes = &expected_attr_list; nexmo_handle_reauth_sms(uid, app_id, message, &existing_prefs); cl_assert(s_performed_store); cl_assert(s_performed_dismiss); }
(nexmo_is_reauth_sms(expected_app_id, expected_message))
<|repo_name|>pebble <|file_sep|>tests/fw/services/notifications/test_nexmo.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "clar.h" #include "services/normal/notifications/ancs/nexmo.h" #include "services/normal/notifications/ancs/ancs_notifications_util.h" #include "services/normal/timeline/attributes_actions.h" // Stubs //////////////////////////////////////////////////////////////// #include "stubs_logging.h" #include "stubs_passert.h" #include "stubs_pbl_malloc.h" // Fakes //////////////////////////////////////////////////////////////// extern const char *NEXMO_REAUTH_STRING; static AttributeList *s_expected_attributes = NULL; static TimelineItemActionGroup *s_expected_actions = NULL; static bool s_performed_store = false; status_t ios_notif_pref_db_store_prefs(const uint8_t *app_id, int length, AttributeList *attr_list, TimelineItemActionGroup *action_group) { const int buf_size = 256; uint8_t buf1[buf_size]; uint8_t buf2[buf_size]; attributes_actions_serialize_payload(attr_list, action_group, buf1, buf_size); attributes_actions_serialize_payload(s_expected_attributes, s_expected_actions, buf2, buf_size); cl_assert_equal_m(buf1, buf2, attributes_actions_get_serialized_payload_size(s_expected_attributes, s_expected_actions)); s_performed_store = true; return S_SUCCESS; } static uint32_t s_expected_uid = 0; static bool s_performed_dismiss = false; void ancs_perform_action(uint32_t notification_uid, uint8_t action_id) { cl_assert_equal_i(notification_uid, s_expected_uid); cl_assert_equal_i(action_id, ActionIDNegative); s_performed_dismiss = true; } void test_nexmo__initialize(void) { s_expected_attributes = NULL; s_expected_actions = NULL; s_performed_store = false; s_expected_uid = INVALID_UID; s_performed_dismiss = false; } void test_nexmo__cleanup(void) { } void test_nexmo__is_reuath_sms(void) { uint8_t expected_app_id_buf[128]; ANCSAttribute *expected_app_id = (ANCSAttribute *)&expected_app_id_buf; expected_app_id->length = strlen(IOS_SMS_APP_ID); memcpy(expected_app_id->value, IOS_SMS_APP_ID, strlen(IOS_SMS_APP_ID)); char valid_message[128]; strcpy(valid_message, "possible preamble "); strcat(valid_message, NEXMO_REAUTH_STRING); strcat(valid_message, " possible postamble"); uint8_t expected_message_buf[128]; ANCSAttribute *expected_message = (ANCSAttribute *)&expected_message_buf; expected_message->length = strlen(valid_message); memcpy(expected_message->value, valid_message, strlen(valid_message)); uint8_t bad_app_id_buf[128]; ANCSAttribute *bad_app_id = (ANCSAttribute *)&bad_app_id_buf; bad_app_id->length = strlen(IOS_MAIL_APP_ID); memcpy(bad_app_id->value, IOS_MAIL_APP_ID, strlen(IOS_MAIL_APP_ID)); const char *bad_string = "Phil was here"; uint8_t bad_message_buf[128]; ANCSAttribute *bad_message = (ANCSAttribute *)&bad_message_buf; bad_message->length = strlen(bad_string); memcpy(bad_message->value, bad_string, strlen(bad_string)); cl_assert<|fim_suffix|>; cl_assert(!nexmo_is_reauth_sms(bad_app_id, expected_message)); cl_assert(!nexmo_is_reauth_sms(expected_app_id, bad_message)); cl_assert(!nexmo_is_reauth_sms(bad_app_id, bad_message)); } void test_nexmo__handle_reuath_sms(void) { // UID const uint32_t uid = 42; s_expected_uid = uid; // App ID uint8_t app_id_buf[128]; ANCSAttribute *app_id = (ANCSAttribute *)&app_id_buf; app_id->length = strlen(IOS_SMS_APP_ID); memcpy(app_id->value, IOS_SMS_APP_ID, strlen(IOS_SMS_APP_ID)); // Message char valid_message[128]; strcpy(valid_message, "possible preamble "); strcat(valid_message, NEXMO_REAUTH_STRING); strcat(valid_message, " possible postamble"); uint8_t message_buf[128]; ANCSAttribute *message = (ANCSAttribute *)&message_buf; message->length = strlen(valid_message); memcpy(message->value, valid_message, strlen(valid_message)); // Existing prefs iOSNotifPrefs existing_prefs = { .attr_list = { .num_attributes = 3, .attributes = (Attribute[]) { { .id = AttributeIdTitle, .cstring = "Title" }, { .id = AttributeIdBody, .cstring = "Body" }, { .id = AttributeIdAppName, .cstring = "Awesome" }, }, }, }; // Make sure that the prefs we store are the existing ones + the reauth msg AttributeList expected_attr_list = { .num_attributes = 4, .attributes = (Attribute[]) { { .id = AttributeIdTitle, .cstring = "Title" }, { .id = AttributeIdBody, .cstring = "Body" }, { .id = AttributeIdAppName, .cstring = "Awesome" }, { .id = AttributeIdAuthCode, .cstring = valid_message }, }, }; s_expected_attributes = &expected_attr_list; nexmo_handle_reauth_sms(uid, app_id, message, &existing_prefs); cl_assert(s_performed_store); cl_assert(s_performed_dismiss); } <|fim_middle|>(nexmo_is_reauth_sms(expected_app_id, expected_message))<|endoftext|>
masked_node
argument_list
tests/fw/test_alarm.c
ons under the License. */ #include "test_alarm_common.h" // Stubs #include "stubs_activity.h" #include "stubs_blob_db_sync.h" #include "stubs_blob_db_sync_util.h" #include "stubs_clock.h" #include "stubs_pbl_malloc.h" /////////////////////////////////////////////////////////////////////////////////////////////////// //! Counter variables static int s_num_timer_register_calls = 0; static int s_alarm_timer_timeout_ms = 0; static int s_snooze_timer_timeout_ms = 0; static int s_snooze_timer_id = 0; /////////////////////////////////////////////////////////////////////////////////////////////////// //! Fakes time_t rtc_get_time(void) { return s_current_day + prv_hours_and_minutes_to_seconds(s_current_hour, s_current_minute); } void rtc_get_time_ms(time_t* out_seconds, uint16_t* out_ms) { *out_ms = 0; *out_seconds = rtc_get_time(); } RtcTicks rtc_get_ticks(void) { return 0; } TimerID new_timer_create(void) { static TimerID s_next_timer_id = 0; s_snooze_timer_id = s_next_timer_id + 1; return ++s_next_timer_id; } bool new_timer_start(TimerID timer_id, uint32_t timeout_ms, NewTimerCallback cb, void *cb_data, uint32_t flags) { s_num_timer_register_calls++; s_snooze_timer_timeout_ms = timeout_ms; return true; } bool new_timer_stop(TimerID timer_id) { s_snooze_timer_timeout_ms = 0; return true; } void new_timer_delete(TimerID timer_id) { s_snooze_timer_timeout_ms = 0; } /////////////////////////////////////////////////////////////////////////////////////////////////// //! Setup void test_alarm__initialize(void) { s_num_timer_register_calls = 0; s_num_timeline_adds = 0; s_num_timeline_removes = 0; s_num_alarm_events_put = 0; s_alarm_timer_timeout_ms = 0; s_snooze_timer_timeout_ms = 0; s_num_alarms_fired = 0; s_current_hour = 0; s_current_minute = 0; // Default to Thursday s_current_day = s_thursday; timeline_item_destroy(s_last_timeline_item_added); s_last_timeline_item_added = NULL; s_last_timeline_item_removed_uuid = (Uuid) {}; fake_spi_flash_init(0, 0x1000000); pfs_init(false); pfs_format(false); cron_service_init(); alarm_init(); alarm_service_enable_alarms(true); } void test_alarm__cleanup(void) { cron_service_deinit(); } /////////////////////////////////////////////////////////////////////////////////////////////////// //! Basic Store / Get Tests void test_alarm__alarm_create_recurring_daily(void) { AlarmId id; id = alarm_create(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_EVERYDAY }); prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); id = alarm_create(&(AlarmInfo) { .hour = 4, .minute = 14, .kind = ALARM_KIND_EVERYDAY }); prv_assert_alarm_config(id, 4, 14, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); id = alarm_create(&(AlarmInfo) { .hour = 5, .minute = 14, .kind = ALARM_KIND_EVERYDAY }); prv_assert_alarm_config(id, 5, 14, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); id = alarm_create(&(AlarmInfo) { .hour = 6, .minute = 14, .kind = ALARM_KIND_EVERYDAY }); prv_assert_alarm_config(id, 6, 14, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); } void test_alarm__alarm_create_recurring_weekends(void) { AlarmId id; id = alarm_create(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_WEEKENDS }); prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_WEEKENDS, s_weekend_schedule); id = alarm_create(&(AlarmInfo) { .hour = 4, .minute = 14, .kind = ALARM_KIND_WEEKENDS }); prv_assert_alarm_config(id, 4, 14, false, ALARM_KIND_WEEKENDS, s_weekend_schedule); id = alarm_create(&(AlarmInfo) { .hour = 5, .minute = 14, .kind = ALARM_KIND_WEEKENDS }); prv_assert_alarm_config(id, 5, 14, false, ALARM_KIND_WEEKENDS, s_weekend_schedule); id = alarm_create(&(AlarmInfo) { .hour = 6, .minute = 14, .kind = ALARM_KIND_WEEKENDS }); prv_assert_alarm_config(id, 6, 14, false, ALARM_KIND_WEEKENDS, s_weekend_schedule); } void test_alarm__alarm_create_recurring_weekdays(void) { AlarmId id; id = alarm_create
; prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); id = alarm_create(&(AlarmInfo) { .hour = 4, .minute = 14, .kind = ALARM_KIND_WEEKDAYS }); prv_assert_alarm_config(id, 4, 14, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); id = alarm_create(&(AlarmInfo) { .hour = 5, .minute = 14, .kind = ALARM_KIND_WEEKDAYS }); prv_assert_alarm_config(id, 5, 14, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); id = alarm_create(&(AlarmInfo) { .hour = 6, .minute = 14, .kind = ALARM_KIND_WEEKDAYS }); prv_assert_alarm_config(id, 6, 14, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); } void test_alarm__alarm_create_just_once(void) { AlarmId id; // It's currently Thursday @ 00:00 bool just_once_schedule_thursday[7] = {false, false, false, false, true, false, false}; id = alarm_create(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_JUST_ONCE }); prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_JUST_ONCE, just_once_schedule_thursday); id = alarm_create(&(AlarmInfo) { .hour = 4, .minute = 14, .kind = ALARM_KIND_JUST_ONCE }); prv_assert_alarm_config(id, 4, 14, false, ALARM_KIND_JUST_ONCE, just_once_schedule_thursday); id = alarm_create(&(AlarmInfo) { .hour = 5, .minute = 14, .kind = ALARM_KIND_JUST_ONCE }); prv_assert_alarm_config(id, 5, 14, false, ALARM_KIND_JUST_ONCE, just_once_schedule_thursday); id = alarm_create(&(AlarmInfo) { .hour = 6, .minute = 14, .kind = ALARM_KIND_JUST_ONCE }); prv_assert_alarm_config(id, 6, 14, false, ALARM_KIND_JUST_ONCE, just_once_schedule_thursday); } void test_alarm__alarm_create_recurring_custom(void) { AlarmId id; bool custom_schedule1[7] = {true, false, true, false, false, true, true}; id = alarm_create(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_CUSTOM, .scheduled_days = &custom_schedule1 }); prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_CUSTOM, custom_schedule1); bool custom_schedule2[7] = {false, false, false, false, false, true, false}; id = alarm_create(&(AlarmInfo) { .hour = 4, .minute = 14, .kind = ALARM_KIND_CUSTOM, .scheduled_days = &custom_schedule2 }); prv_assert_alarm_config(id, 4, 14, false, ALARM_KIND_CUSTOM, custom_schedule2); bool custom_schedule3[7] = {true, true, true, true, true, true, true}; id = alarm_create(&(AlarmInfo) { .hour = 5, .minute = 14, .kind = ALARM_KIND_CUSTOM, .scheduled_days = &custom_schedule3 }); prv_assert_alarm_config(id, 5, 14, false, ALARM_KIND_CUSTOM, custom_schedule3); // FIXME: bool custom_schedule4[7] = {false, false, false, false, false, false, false}; id = alarm_create(&(AlarmInfo) { .hour = 6, .minute = 14, .kind = ALARM_KIND_CUSTOM, .scheduled_days = &custom_schedule4 }); prv_assert_alarm_config(id, 6, 14, false, ALARM_KIND_CUSTOM, custom_schedule4); } void test_alarm__alarm_set_time(void) { AlarmId id1, id2; id1 = alarm_create(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_EVERYDAY }); prv_assert_alarm_config(id1, 3, 14, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); alarm_set_time(id1, 5, 6); prv_assert_alarm_config(id1, 5, 6, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); id2 = alarm_create(&(AlarmInfo) { .hour = 4, .minute = 14, .kind = ALARM_KIND_WEEKDAYS }); prv_assert_alarm_config(id2, 4, 14, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); alarm_set_time(id2, 23, 56); prv_assert_alarm_config(id2, 23, 56, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); alarm_set_time(id1, 15, 16); prv_assert_alarm_config(id1, 15, 16, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); alarm_set_time(id2, 23, 46); prv_assert_alarm_config(id2, 23, 46, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); } void test_alarm__alarm_set_recurring_daily(void) { AlarmId id; id = alarm_create(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_WEEKENDS }); prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_WEEKENDS, s_weekend_schedule); alarm_set_kind(id, ALARM_KIND_EVERYDAY); prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_EVERYDAY, s
(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_WEEKDAYS })
<|repo_name|>pebble <|file_sep|>tests/fw/test_alarm.c <|fim_prefix|>ons under the License. */ #include "test_alarm_common.h" // Stubs #include "stubs_activity.h" #include "stubs_blob_db_sync.h" #include "stubs_blob_db_sync_util.h" #include "stubs_clock.h" #include "stubs_pbl_malloc.h" /////////////////////////////////////////////////////////////////////////////////////////////////// //! Counter variables static int s_num_timer_register_calls = 0; static int s_alarm_timer_timeout_ms = 0; static int s_snooze_timer_timeout_ms = 0; static int s_snooze_timer_id = 0; /////////////////////////////////////////////////////////////////////////////////////////////////// //! Fakes time_t rtc_get_time(void) { return s_current_day + prv_hours_and_minutes_to_seconds(s_current_hour, s_current_minute); } void rtc_get_time_ms(time_t* out_seconds, uint16_t* out_ms) { *out_ms = 0; *out_seconds = rtc_get_time(); } RtcTicks rtc_get_ticks(void) { return 0; } TimerID new_timer_create(void) { static TimerID s_next_timer_id = 0; s_snooze_timer_id = s_next_timer_id + 1; return ++s_next_timer_id; } bool new_timer_start(TimerID timer_id, uint32_t timeout_ms, NewTimerCallback cb, void *cb_data, uint32_t flags) { s_num_timer_register_calls++; s_snooze_timer_timeout_ms = timeout_ms; return true; } bool new_timer_stop(TimerID timer_id) { s_snooze_timer_timeout_ms = 0; return true; } void new_timer_delete(TimerID timer_id) { s_snooze_timer_timeout_ms = 0; } /////////////////////////////////////////////////////////////////////////////////////////////////// //! Setup void test_alarm__initialize(void) { s_num_timer_register_calls = 0; s_num_timeline_adds = 0; s_num_timeline_removes = 0; s_num_alarm_events_put = 0; s_alarm_timer_timeout_ms = 0; s_snooze_timer_timeout_ms = 0; s_num_alarms_fired = 0; s_current_hour = 0; s_current_minute = 0; // Default to Thursday s_current_day = s_thursday; timeline_item_destroy(s_last_timeline_item_added); s_last_timeline_item_added = NULL; s_last_timeline_item_removed_uuid = (Uuid) {}; fake_spi_flash_init(0, 0x1000000); pfs_init(false); pfs_format(false); cron_service_init(); alarm_init(); alarm_service_enable_alarms(true); } void test_alarm__cleanup(void) { cron_service_deinit(); } /////////////////////////////////////////////////////////////////////////////////////////////////// //! Basic Store / Get Tests void test_alarm__alarm_create_recurring_daily(void) { AlarmId id; id = alarm_create(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_EVERYDAY }); prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); id = alarm_create(&(AlarmInfo) { .hour = 4, .minute = 14, .kind = ALARM_KIND_EVERYDAY }); prv_assert_alarm_config(id, 4, 14, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); id = alarm_create(&(AlarmInfo) { .hour = 5, .minute = 14, .kind = ALARM_KIND_EVERYDAY }); prv_assert_alarm_config(id, 5, 14, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); id = alarm_create(&(AlarmInfo) { .hour = 6, .minute = 14, .kind = ALARM_KIND_EVERYDAY }); prv_assert_alarm_config(id, 6, 14, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); } void test_alarm__alarm_create_recurring_weekends(void) { AlarmId id; id = alarm_create(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_WEEKENDS }); prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_WEEKENDS, s_weekend_schedule); id = alarm_create(&(AlarmInfo) { .hour = 4, .minute = 14, .kind = ALARM_KIND_WEEKENDS }); prv_assert_alarm_config(id, 4, 14, false, ALARM_KIND_WEEKENDS, s_weekend_schedule); id = alarm_create(&(AlarmInfo) { .hour = 5, .minute = 14, .kind = ALARM_KIND_WEEKENDS }); prv_assert_alarm_config(id, 5, 14, false, ALARM_KIND_WEEKENDS, s_weekend_schedule); id = alarm_create(&(AlarmInfo) { .hour = 6, .minute = 14, .kind = ALARM_KIND_WEEKENDS }); prv_assert_alarm_config(id, 6, 14, false, ALARM_KIND_WEEKENDS, s_weekend_schedule); } void test_alarm__alarm_create_recurring_weekdays(void) { AlarmId id; id = alarm_create<|fim_suffix|>; prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); id = alarm_create(&(AlarmInfo) { .hour = 4, .minute = 14, .kind = ALARM_KIND_WEEKDAYS }); prv_assert_alarm_config(id, 4, 14, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); id = alarm_create(&(AlarmInfo) { .hour = 5, .minute = 14, .kind = ALARM_KIND_WEEKDAYS }); prv_assert_alarm_config(id, 5, 14, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); id = alarm_create(&(AlarmInfo) { .hour = 6, .minute = 14, .kind = ALARM_KIND_WEEKDAYS }); prv_assert_alarm_config(id, 6, 14, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); } void test_alarm__alarm_create_just_once(void) { AlarmId id; // It's currently Thursday @ 00:00 bool just_once_schedule_thursday[7] = {false, false, false, false, true, false, false}; id = alarm_create(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_JUST_ONCE }); prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_JUST_ONCE, just_once_schedule_thursday); id = alarm_create(&(AlarmInfo) { .hour = 4, .minute = 14, .kind = ALARM_KIND_JUST_ONCE }); prv_assert_alarm_config(id, 4, 14, false, ALARM_KIND_JUST_ONCE, just_once_schedule_thursday); id = alarm_create(&(AlarmInfo) { .hour = 5, .minute = 14, .kind = ALARM_KIND_JUST_ONCE }); prv_assert_alarm_config(id, 5, 14, false, ALARM_KIND_JUST_ONCE, just_once_schedule_thursday); id = alarm_create(&(AlarmInfo) { .hour = 6, .minute = 14, .kind = ALARM_KIND_JUST_ONCE }); prv_assert_alarm_config(id, 6, 14, false, ALARM_KIND_JUST_ONCE, just_once_schedule_thursday); } void test_alarm__alarm_create_recurring_custom(void) { AlarmId id; bool custom_schedule1[7] = {true, false, true, false, false, true, true}; id = alarm_create(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_CUSTOM, .scheduled_days = &custom_schedule1 }); prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_CUSTOM, custom_schedule1); bool custom_schedule2[7] = {false, false, false, false, false, true, false}; id = alarm_create(&(AlarmInfo) { .hour = 4, .minute = 14, .kind = ALARM_KIND_CUSTOM, .scheduled_days = &custom_schedule2 }); prv_assert_alarm_config(id, 4, 14, false, ALARM_KIND_CUSTOM, custom_schedule2); bool custom_schedule3[7] = {true, true, true, true, true, true, true}; id = alarm_create(&(AlarmInfo) { .hour = 5, .minute = 14, .kind = ALARM_KIND_CUSTOM, .scheduled_days = &custom_schedule3 }); prv_assert_alarm_config(id, 5, 14, false, ALARM_KIND_CUSTOM, custom_schedule3); // FIXME: bool custom_schedule4[7] = {false, false, false, false, false, false, false}; id = alarm_create(&(AlarmInfo) { .hour = 6, .minute = 14, .kind = ALARM_KIND_CUSTOM, .scheduled_days = &custom_schedule4 }); prv_assert_alarm_config(id, 6, 14, false, ALARM_KIND_CUSTOM, custom_schedule4); } void test_alarm__alarm_set_time(void) { AlarmId id1, id2; id1 = alarm_create(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_EVERYDAY }); prv_assert_alarm_config(id1, 3, 14, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); alarm_set_time(id1, 5, 6); prv_assert_alarm_config(id1, 5, 6, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); id2 = alarm_create(&(AlarmInfo) { .hour = 4, .minute = 14, .kind = ALARM_KIND_WEEKDAYS }); prv_assert_alarm_config(id2, 4, 14, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); alarm_set_time(id2, 23, 56); prv_assert_alarm_config(id2, 23, 56, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); alarm_set_time(id1, 15, 16); prv_assert_alarm_config(id1, 15, 16, false, ALARM_KIND_EVERYDAY, s_every_day_schedule); alarm_set_time(id2, 23, 46); prv_assert_alarm_config(id2, 23, 46, false, ALARM_KIND_WEEKDAYS, s_weekday_schedule); } void test_alarm__alarm_set_recurring_daily(void) { AlarmId id; id = alarm_create(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_WEEKENDS }); prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_WEEKENDS, s_weekend_schedule); alarm_set_kind(id, ALARM_KIND_EVERYDAY); prv_assert_alarm_config(id, 3, 14, false, ALARM_KIND_EVERYDAY, s<|fim_middle|>(&(AlarmInfo) { .hour = 3, .minute = 14, .kind = ALARM_KIND_WEEKDAYS })<|endoftext|>
masked_node
call_expression
src/fw/applib/voice/loading_layer.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "loading_layer.h" #include "applib/graphics/gtypes.h" #include "applib/ui/property_animation.h" #include <string.h> void loading_layer_init(LoadingLayer *loading_layer, const GRect *frame) { *loading_layer = (LoadingLayer) { .full_frame = *frame }; ProgressLayer *progress_layer = &loading_layer->progress_layer; progress_layer_init(progress_layer, frame); progress_layer_set_corner_radius(progress_layer, PROGRESS_SUGGESTED_CORNER_RADIUS); } void loading_layer_deinit(LoadingLayer *loading_layer) { loading_layer_pause(loading_layer); progress_layer_deinit(&loading_layer->progress_layer); } void loading_layer_shrink(LoadingLayer *loading_layer, uint32_t delay, uint32_t duration, AnimationStoppedHandler stopped_handler, void *context) { loading_layer_pause(loading_layer);
; GRect *start = &loading_layer->full_frame; GRect stop = *start; stop.origin.x += stop.size.w; stop.size.w = 0; PropertyAnimation *prop_anim = property_animation_create_layer_frame( (Layer *)loading_layer, start, &stop); if (!prop_anim) { return; } Animation *animation = property_animation_get_animation(prop_anim); // If we failed, pause on the screen for a little. animation_set_delay(animation, delay); animation_set_duration(animation, duration); animation_set_curve(animation, AnimationCurveEaseOut); animation_set_handlers(animation, (AnimationHandlers) { .stopped = stopped_handler }, context); loading_layer->animation = animation; animation_schedule(animation); } void loading_layer_pause(LoadingLayer *loading_layer) { if (animation_is_scheduled(loading_layer->animation)) { animation_unschedule(loading_layer->animation); } } void loading_layer_grow(LoadingLayer *loading_layer, uint32_t delay, uint32_t duration) { loading_layer_pause(loading_layer); if (duration == 0) { layer_set_frame((Layer *)loading_layer, &loading_layer->full_frame); return; } GRect start = loading_layer->full_frame; start.size.w = 0; layer_set_frame((Layer *)loading_layer, &start); PropertyAnimation *prop_anim = property_animation_create_layer_frame( (Layer *)loading_layer, &start, &loading_layer->full_frame); if (!prop_anim) { return; } Animation *animation = property_animation_get_animation(prop_anim); animation_set_delay(animation, delay); animation_set_duration(animation, duration); animation_set_curve(animation, AnimationCurveEaseOut); loading_layer->animation = animation; animation_schedule(animation); }
layer_set_frame((Layer *)loading_layer, &loading_layer->full_frame)
<|repo_name|>pebble <|file_sep|>src/fw/applib/voice/loading_layer.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "loading_layer.h" #include "applib/graphics/gtypes.h" #include "applib/ui/property_animation.h" #include <string.h> void loading_layer_init(LoadingLayer *loading_layer, const GRect *frame) { *loading_layer = (LoadingLayer) { .full_frame = *frame }; ProgressLayer *progress_layer = &loading_layer->progress_layer; progress_layer_init(progress_layer, frame); progress_layer_set_corner_radius(progress_layer, PROGRESS_SUGGESTED_CORNER_RADIUS); } void loading_layer_deinit(LoadingLayer *loading_layer) { loading_layer_pause(loading_layer); progress_layer_deinit(&loading_layer->progress_layer); } void loading_layer_shrink(LoadingLayer *loading_layer, uint32_t delay, uint32_t duration, AnimationStoppedHandler stopped_handler, void *context) { loading_layer_pause(loading_layer); <|fim_suffix|>; GRect *start = &loading_layer->full_frame; GRect stop = *start; stop.origin.x += stop.size.w; stop.size.w = 0; PropertyAnimation *prop_anim = property_animation_create_layer_frame( (Layer *)loading_layer, start, &stop); if (!prop_anim) { return; } Animation *animation = property_animation_get_animation(prop_anim); // If we failed, pause on the screen for a little. animation_set_delay(animation, delay); animation_set_duration(animation, duration); animation_set_curve(animation, AnimationCurveEaseOut); animation_set_handlers(animation, (AnimationHandlers) { .stopped = stopped_handler }, context); loading_layer->animation = animation; animation_schedule(animation); } void loading_layer_pause(LoadingLayer *loading_layer) { if (animation_is_scheduled(loading_layer->animation)) { animation_unschedule(loading_layer->animation); } } void loading_layer_grow(LoadingLayer *loading_layer, uint32_t delay, uint32_t duration) { loading_layer_pause(loading_layer); if (duration == 0) { layer_set_frame((Layer *)loading_layer, &loading_layer->full_frame); return; } GRect start = loading_layer->full_frame; start.size.w = 0; layer_set_frame((Layer *)loading_layer, &start); PropertyAnimation *prop_anim = property_animation_create_layer_frame( (Layer *)loading_layer, &start, &loading_layer->full_frame); if (!prop_anim) { return; } Animation *animation = property_animation_get_animation(prop_anim); animation_set_delay(animation, delay); animation_set_duration(animation, duration); animation_set_curve(animation, AnimationCurveEaseOut); loading_layer->animation = animation; animation_schedule(animation); } <|fim_middle|>layer_set_frame((Layer *)loading_layer, &loading_layer->full_frame)<|endoftext|>
masked_node
call_expression
src/fw/services/normal/timeline/layout_node.c
rics); GTextNodeVertical *vertical_node = graphics_text_node_create_vertical(num_nodes); for (unsigned int i = 0; i < num_metrics; i++) { const char *name = string_list_get_at(names, i); const char *value = string_list_get_at(values, i); if (!name || !value) { break; } TimelineResourceInfo icon_info = { .res_id = icons->values[i], .app_id = &layout->info->app_id, }; AppResourceInfo icon_res_info; timeline_resources_get_id(&icon_info, TimelineResourceSizeTiny, &icon_res_info); const LayoutNodeConstructorConfig metric_config = { .extent.node.type = LayoutNodeType_Constructor, .constructor = prv_metric_constructor, .context = &(MetricContext) { .index = i, .name = name, .value = value, .icon_info = &icon_res_info, .icon_layer = i == 0 ? &layout->icon_layer : layout->metric_icon_layers[i - 1], }, }; GTextNodeText *metric_node = (GTextNodeText *)layout_create_text_node_from_config( layout_ref, &metric_config.extent.node); prv_add_metric(layout, vertical_node, i, &metric_node->node); } return vertical_node; } static GTextNode *prv_create_metrics_node(const LayoutLayer *layout, const LayoutNodeConfig *config) { GTextNode *node = &layout_create_metrics_node(layout)->container.node; prv_set_text_node_extent(node, (LayoutNodeExtentConfig *)config); return node; } static GTextNode *prv_create_icon_node_from_config(const LayoutLayer *layout, const LayoutNodeIconConfig *config) { KinoReel *icon_reel = kino_reel_create_with_resource_system(config->res_info->res_app_num, config->res_info->res_id); if (!icon_reel) { return NULL; } KinoLayer *icon_layer = kino_layer_create((GRect) { .size = kino_reel_get_size(icon_reel) }); *config->icon_layer = icon_layer; kino_layer_set_alignment(icon_layer, config->align); kino_layer_set_reel(icon_layer, icon_reel, true /* take_ownership */); layer_add_child((void *)&layout->layer, &icon_layer->layer); GTextNodeCustom *custom = layout_node_create_kino_layer_wrapper(icon_layer); prv_set_text_node_extent(&custom->node, &config->extent); return &custom->node; } GTextNode *layout_create_text_node_from_config(const LayoutLayer *layout, const LayoutNodeConfig *config) { if (!config) { return NULL; } switch (config->type) { case LayoutNodeType_TextAttribute: return &prv_create_text_attribute_node_from_config( layout, (LayoutNodeTextAttributeConfig *)config)->node; case LayoutNodeType_TextBuffer: return &prv_create_text_buffer_node_from_config( layout, (LayoutNodeTextBufferConfig *)config)->node; case LayoutNodeType_TextDynamic: return &prv_create_text_dynamic_node_from_config( layout, (LayoutNodeTextDynamicConfig *)config)->text.node; case LayoutNodeType_Text: return &prv_create_text_node_from_config(layout, (LayoutNodeTextConfig *)config)->node; case LayoutNodeType_Horizontal: return &prv_create_horizontal_container_node_from_config( layout, (LayoutNodeHorizontalConfig *)config)->container.node; case LayoutNodeType_Vertical: return &prv_create_vertical_container_node_from_config( layout, (LayoutNodeVerticalConfig *)config)->container.node; case LayoutNodeType_Constructor: return prv_create_node_from_constructor_config(layout, (LayoutNodeConstructorConfig *)config); case LayoutNodeType_Icon: #if !PLATFORM_TINTIN return prv_create_icon_node_from_config(layout, (LayoutNodeIconConfig *)config); #else return NULL; #endif case LayoutNodeType_TimelineIcon: return prv_create_timeline_icon_node_from_config(layout, (LayoutNodeExtentConfig *)config); case LayoutNodeType_TimelinePageBreak: return &
->node; case LayoutNodeType_TimelineMetrics: #if !PLATFORM_TINTIN return prv_create_metrics_node(layout, config); #else return NULL; #endif case LayoutNodeType_HeadingsParagraphs: return prv_create_headings_paragraphs_node( layout, (LayoutNodeHeadingsParagraphsConfig *)config); } return NULL; } static void prv_kino_layer_wrapper_callback(GContext *ctx, const GRect *box, const GTextNodeDrawConfig *config, bool render, GSize *size_out, void *user_data) { KinoLayer *kino_layer = user_data; GRect frame = kino_layer->layer.frame; if (!render) { grect_align(&frame, box, kino_layer_get_alignment(kino_layer), false); frame.origin.y = box->origin.y; layer_set_frame(&kino_layer->layer, &frame); } if (size_out) { *size_out = frame.size; } } GTextNodeCustom *layout_node_create_kino_layer_wrapper(KinoLayer *kino_layer) { return graphics_text_node_create_custom(prv_kino_layer_wrapper_callback, (void *)kino_layer); }
timeline_layout_create_page_break_node((const TimelineLayout *)layout)
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/timeline/layout_node.c <|fim_prefix|>rics); GTextNodeVertical *vertical_node = graphics_text_node_create_vertical(num_nodes); for (unsigned int i = 0; i < num_metrics; i++) { const char *name = string_list_get_at(names, i); const char *value = string_list_get_at(values, i); if (!name || !value) { break; } TimelineResourceInfo icon_info = { .res_id = icons->values[i], .app_id = &layout->info->app_id, }; AppResourceInfo icon_res_info; timeline_resources_get_id(&icon_info, TimelineResourceSizeTiny, &icon_res_info); const LayoutNodeConstructorConfig metric_config = { .extent.node.type = LayoutNodeType_Constructor, .constructor = prv_metric_constructor, .context = &(MetricContext) { .index = i, .name = name, .value = value, .icon_info = &icon_res_info, .icon_layer = i == 0 ? &layout->icon_layer : layout->metric_icon_layers[i - 1], }, }; GTextNodeText *metric_node = (GTextNodeText *)layout_create_text_node_from_config( layout_ref, &metric_config.extent.node); prv_add_metric(layout, vertical_node, i, &metric_node->node); } return vertical_node; } static GTextNode *prv_create_metrics_node(const LayoutLayer *layout, const LayoutNodeConfig *config) { GTextNode *node = &layout_create_metrics_node(layout)->container.node; prv_set_text_node_extent(node, (LayoutNodeExtentConfig *)config); return node; } static GTextNode *prv_create_icon_node_from_config(const LayoutLayer *layout, const LayoutNodeIconConfig *config) { KinoReel *icon_reel = kino_reel_create_with_resource_system(config->res_info->res_app_num, config->res_info->res_id); if (!icon_reel) { return NULL; } KinoLayer *icon_layer = kino_layer_create((GRect) { .size = kino_reel_get_size(icon_reel) }); *config->icon_layer = icon_layer; kino_layer_set_alignment(icon_layer, config->align); kino_layer_set_reel(icon_layer, icon_reel, true /* take_ownership */); layer_add_child((void *)&layout->layer, &icon_layer->layer); GTextNodeCustom *custom = layout_node_create_kino_layer_wrapper(icon_layer); prv_set_text_node_extent(&custom->node, &config->extent); return &custom->node; } GTextNode *layout_create_text_node_from_config(const LayoutLayer *layout, const LayoutNodeConfig *config) { if (!config) { return NULL; } switch (config->type) { case LayoutNodeType_TextAttribute: return &prv_create_text_attribute_node_from_config( layout, (LayoutNodeTextAttributeConfig *)config)->node; case LayoutNodeType_TextBuffer: return &prv_create_text_buffer_node_from_config( layout, (LayoutNodeTextBufferConfig *)config)->node; case LayoutNodeType_TextDynamic: return &prv_create_text_dynamic_node_from_config( layout, (LayoutNodeTextDynamicConfig *)config)->text.node; case LayoutNodeType_Text: return &prv_create_text_node_from_config(layout, (LayoutNodeTextConfig *)config)->node; case LayoutNodeType_Horizontal: return &prv_create_horizontal_container_node_from_config( layout, (LayoutNodeHorizontalConfig *)config)->container.node; case LayoutNodeType_Vertical: return &prv_create_vertical_container_node_from_config( layout, (LayoutNodeVerticalConfig *)config)->container.node; case LayoutNodeType_Constructor: return prv_create_node_from_constructor_config(layout, (LayoutNodeConstructorConfig *)config); case LayoutNodeType_Icon: #if !PLATFORM_TINTIN return prv_create_icon_node_from_config(layout, (LayoutNodeIconConfig *)config); #else return NULL; #endif case LayoutNodeType_TimelineIcon: return prv_create_timeline_icon_node_from_config(layout, (LayoutNodeExtentConfig *)config); case LayoutNodeType_TimelinePageBreak: return &<|fim_suffix|>->node; case LayoutNodeType_TimelineMetrics: #if !PLATFORM_TINTIN return prv_create_metrics_node(layout, config); #else return NULL; #endif case LayoutNodeType_HeadingsParagraphs: return prv_create_headings_paragraphs_node( layout, (LayoutNodeHeadingsParagraphsConfig *)config); } return NULL; } static void prv_kino_layer_wrapper_callback(GContext *ctx, const GRect *box, const GTextNodeDrawConfig *config, bool render, GSize *size_out, void *user_data) { KinoLayer *kino_layer = user_data; GRect frame = kino_layer->layer.frame; if (!render) { grect_align(&frame, box, kino_layer_get_alignment(kino_layer), false); frame.origin.y = box->origin.y; layer_set_frame(&kino_layer->layer, &frame); } if (size_out) { *size_out = frame.size; } } GTextNodeCustom *layout_node_create_kino_layer_wrapper(KinoLayer *kino_layer) { return graphics_text_node_create_custom(prv_kino_layer_wrapper_callback, (void *)kino_layer); } <|fim_middle|>timeline_layout_create_page_break_node((const TimelineLayout *)layout)<|endoftext|>
prefix_only
argument_list
src/fw/services/normal/bluetooth/bluetooth_persistent_storage.c
initialized, make sure there is no code // that tries to use the BT stack in this path. s_db_mutex = mutex_create(); prv_load_data_from_prf(); // Load cached capability bits from flash prv_load_cached_system_capabilities(&s_cached_system_capabilities); } static void prv_delete_all_pairings_itr(SettingsFile *old_file, SettingsFile *new_file, SettingsRecordInfo *info, void *context) { if (info->key_len == sizeof(BTBondingID)) { // Skip pairing entries return; } // Re-write non-pairing entries void *key = kernel_zalloc_check(info->key_len); info->get_key(old_file, key, info->key_len); void *data = kernel_malloc_check(info->val_len); info->get_val(old_file, data, info->val_len); settings_file_set(new_file, key, info->key_len, &data, info->val_len); kernel_free(key); kernel_free(data); } void bt_persistent_storage_delete_all_pairings(void) { prv_lock(); { SettingsFile fd; status_t rv = settings_file_open(&fd, BT_PERSISTENT_STORAGE_FILE_NAME, BT_PERSISTENT_STORAGE_FILE_SIZE); if (rv) { return; } settings_file_rewrite(&fd, prv_delete_all_pairings_itr, NULL); settings_file_close(&fd); } prv_unlock(); shared_prf_storage_erase_ble_pairing_data(); if (bt_driver_supports_bt_classic()) { shared_prf_storage_erase_bt_classic_pairing_data(); } } static void prv_dump_bonding_db_data(char display_buf[DISPLAY_BUF_LEN], BTBondingID bond_id, BtPersistBondingData *data) { bool matches_prf; if (data->type == BtPersistBondingTypeBTClassic) { prompt_send_response_fmt(display_buf, DISPLAY_BUF_LEN, "Classic Key %d", (int)bond_id); bluetooth_persistent_storage_debug_dump_classic_pairing_info( display_buf, &data->bt_classic_data.addr, &data->bt_classic_data.name[0], &data->bt_classic_data.link_key, data->bt_classic_data.platform_bits); BtPersistBondingBTClassicData sprf_bt_data = {}; shared_prf_storage_get_bt_classic_pairing_data( &sprf_bt_data.addr, &sprf_bt_data.name[0], &sprf_bt_data.link_key, &sprf_bt_data.platform_bits); matches_prf = memcmp(&sprf_bt_data, &data->bt_classic_data, sizeof(sprf_bt_data)) == 0; prompt_send_response_fmt(display_buf, DISPLAY_BUF_LEN, " BT Pairing Data matches Shared PRF: %s", bool_to_str(matches_prf)); } else if (data->type == BtPersistBondingTypeBLE) { prompt_send_response_fmt(display_buf, DISPLAY_BUF_LEN, "LE Key %d", (int)bond_id); prompt_send_response_fmt(display_buf, DISPLAY_BUF_LEN, " ANCS: %d Gateway: %d Req Pin: %d", (int)data->ble_data.supports_ancs, (int)data->ble_data.is_gateway, (int)data->ble_data.requires_address_pinning); prompt_send_response_fmt(display_buf, DISPLAY_BUF_LEN, " Name: %s", data->ble_data.name); SMPairingInfo info = {}; bt_persistent_storage_assign_sm_pairing_info(&info, &data->ble_data.pairing_info); bluetooth_persistent_storage_debug_dump_ble_pairing_info(&display_buf[0], &info); // does this info match the key stored in shared resources SMPairingInfo sprf_info = {}; bool requires_address_pinning; uint8_t flags; shared_prf_storage_get_ble_pairing_data(&sprf_info, NULL, &requires_address_pinning, &flags); matches_prf = (memcmp(&sprf_info, &info, sizeof(sprf_info)) == 0); matches_prf &= (requires_address_pinning == data->ble_data.requires_address_pinning); matches_prf &= (flags == data->ble_data.flags); prompt_send_response_fmt(display_buf, DISPLAY_BUF_LEN, " SMPairingInfo matches Shared PRF: %s", bool_to_str(matches_prf)); } else { prompt_send_response("Unhandled type of GapBondingDB Data!"); PBL_HEXDUMP_D_PROMPT
(LOG_LEVEL_DEBUG, (uint8_t *)&data, sizeof(*data))
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/bluetooth/bluetooth_persistent_storage.c <|fim_prefix|>initialized, make sure there is no code // that tries to use the BT stack in this path. s_db_mutex = mutex_create(); prv_load_data_from_prf(); // Load cached capability bits from flash prv_load_cached_system_capabilities(&s_cached_system_capabilities); } static void prv_delete_all_pairings_itr(SettingsFile *old_file, SettingsFile *new_file, SettingsRecordInfo *info, void *context) { if (info->key_len == sizeof(BTBondingID)) { // Skip pairing entries return; } // Re-write non-pairing entries void *key = kernel_zalloc_check(info->key_len); info->get_key(old_file, key, info->key_len); void *data = kernel_malloc_check(info->val_len); info->get_val(old_file, data, info->val_len); settings_file_set(new_file, key, info->key_len, &data, info->val_len); kernel_free(key); kernel_free(data); } void bt_persistent_storage_delete_all_pairings(void) { prv_lock(); { SettingsFile fd; status_t rv = settings_file_open(&fd, BT_PERSISTENT_STORAGE_FILE_NAME, BT_PERSISTENT_STORAGE_FILE_SIZE); if (rv) { return; } settings_file_rewrite(&fd, prv_delete_all_pairings_itr, NULL); settings_file_close(&fd); } prv_unlock(); shared_prf_storage_erase_ble_pairing_data(); if (bt_driver_supports_bt_classic()) { shared_prf_storage_erase_bt_classic_pairing_data(); } } static void prv_dump_bonding_db_data(char display_buf[DISPLAY_BUF_LEN], BTBondingID bond_id, BtPersistBondingData *data) { bool matches_prf; if (data->type == BtPersistBondingTypeBTClassic) { prompt_send_response_fmt(display_buf, DISPLAY_BUF_LEN, "Classic Key %d", (int)bond_id); bluetooth_persistent_storage_debug_dump_classic_pairing_info( display_buf, &data->bt_classic_data.addr, &data->bt_classic_data.name[0], &data->bt_classic_data.link_key, data->bt_classic_data.platform_bits); BtPersistBondingBTClassicData sprf_bt_data = {}; shared_prf_storage_get_bt_classic_pairing_data( &sprf_bt_data.addr, &sprf_bt_data.name[0], &sprf_bt_data.link_key, &sprf_bt_data.platform_bits); matches_prf = memcmp(&sprf_bt_data, &data->bt_classic_data, sizeof(sprf_bt_data)) == 0; prompt_send_response_fmt(display_buf, DISPLAY_BUF_LEN, " BT Pairing Data matches Shared PRF: %s", bool_to_str(matches_prf)); } else if (data->type == BtPersistBondingTypeBLE) { prompt_send_response_fmt(display_buf, DISPLAY_BUF_LEN, "LE Key %d", (int)bond_id); prompt_send_response_fmt(display_buf, DISPLAY_BUF_LEN, " ANCS: %d Gateway: %d Req Pin: %d", (int)data->ble_data.supports_ancs, (int)data->ble_data.is_gateway, (int)data->ble_data.requires_address_pinning); prompt_send_response_fmt(display_buf, DISPLAY_BUF_LEN, " Name: %s", data->ble_data.name); SMPairingInfo info = {}; bt_persistent_storage_assign_sm_pairing_info(&info, &data->ble_data.pairing_info); bluetooth_persistent_storage_debug_dump_ble_pairing_info(&display_buf[0], &info); // does this info match the key stored in shared resources SMPairingInfo sprf_info = {}; bool requires_address_pinning; uint8_t flags; shared_prf_storage_get_ble_pairing_data(&sprf_info, NULL, &requires_address_pinning, &flags); matches_prf = (memcmp(&sprf_info, &info, sizeof(sprf_info)) == 0); matches_prf &= (requires_address_pinning == data->ble_data.requires_address_pinning); matches_prf &= (flags == data->ble_data.flags); prompt_send_response_fmt(display_buf, DISPLAY_BUF_LEN, " SMPairingInfo matches Shared PRF: %s", bool_to_str(matches_prf)); } else { prompt_send_response("Unhandled type of GapBondingDB Data!"); PBL_HEXDUMP_D_PROMPT<|fim_suffix|><|fim_middle|>(LOG_LEVEL_DEBUG, (uint8_t *)&data, sizeof(*data))<|endoftext|>
masked_node
call_expression
tests/fw/comm/test_ppogatt.c
d: cl_assert_equal_i(ppogatt_client_count(), 1); Transport *client = ppogatt_client_for_uuid(&metas[i].meta->app_uuid); cl_assert_equal_i(ppogatt_get_destination(client), metas[i].expected_destination); ppogatt_close(client); } } void test_ppogatt__handles_unsupported_meta_ppogatt_version(void) { PPoGATTMetaV0 future_meta_non_compatible = s_meta_v0_system; future_meta_non_compatible.ppogatt_min_version = 0xaa; future_meta_non_compatible.ppogatt_max_version = 0xff; prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &future_meta_non_compatible, sizeof(future_meta_non_compatible), BLEGATTErrorSuccess); // No client created: cl_assert_equal_i(ppogatt_client_count(), 0); cl_assert_equal_b(ppogatt_has_client_for_uuid(&future_meta_non_compatible.app_uuid), false); } void test_ppogatt__handles_invalid_uuid_meta(void) { PPoGATTMetaV0 meta_invalid_uuid = s_meta_v0_system; meta_invalid_uuid.app_uuid = UUID_INVALID; prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &meta_invalid_uuid, sizeof(meta_invalid_uuid), BLEGATTErrorSuccess); // No client created: cl_assert_equal_i(ppogatt_client_count(), 0); cl_assert_equal_b(ppogatt_has_client_for_uuid(&meta_invalid_uuid.app_uuid), false); } void test_ppogatt__deletes_existing_client_after_rediscovery(void) { prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &s_meta_v0_system, sizeof(s_meta_v0_system), BLEGATTErrorSuccess); // Client created: cl_assert_equal_i(ppogatt_client_count(), 1); cl_assert_equal_b(ppogatt_has_client_for_uuid(&s_meta_v0_system.app_uuid), true); Transport *client = ppogatt_client_for_uuid(&s_meta_v0_system.app_uuid); // Rediscovery: ppogatt_invalidate_all_references(); prv_notify_services_discovered(1); // Still one client: cl_assert_equal_i(ppogatt_client_count(), 1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &s_meta_v0_system, sizeof(s_meta_v0_system), BLEGATTErrorSuccess); // Still one client: cl_assert_equal_i(ppogatt_client_count(), 1); cl_assert_equal_b(ppogatt_has_client_for_uuid(&s_meta_v0_system.app_uuid), true); Transport *client2 = ppogatt_client_for_uuid(&s_meta_v0_system.app_uuid); } void test_ppogatt__invalidate_characteristic_refs_immediately_after_update(void) { prv_notify_services_discovered(1); ppogatt_handle_service_removed(&s_characteristics[0][0], PPoGATTCharacteristicNum); const bool can_handle = ppogatt_can_handle_characteristic(s_characteristics[0][PPoGATTCharacteristicData]); cl_assert_equal_b(can_handle, false); } void test_ppogatt__handle_subscribe_to_unknown_characteristic(void) { ppogatt_handle_subscribe(s_unknown_characteristics, BLESubscriptionNotifications, BLEGATTErrorSuccess); // Expect to unsubscribe from the unknown characteristic: fake_gatt_client_subscriptions_assert_subscribe(s_unknown_characteristics, BLESubscriptionNone, GAPLEClientKernel); } void test_ppogatt__cleanup_client_when_meta_read_fails(void) { fake_gatt_client_op_set_read_return_value(BTErrnoInvalidParameter); prv_notify_services_discovered(1); cl_assert_equal_i(ppogatt_client_count(), 0); } void test_ppogatt__cleanup_client_when_meta_read_gets_error_response(void) {
; prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], NULL, 0, BLEGATTErrorInvalidHandle); cl_assert_equal_i(ppogatt_client_count(), 0); } void test_ppogatt__cleanup_client_when_data_subscription_cccd_write_failed(void) { fake_gatt_client_subscriptions_set_subscribe_return_value(BTErrnoInvalidParameter); prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &s_meta_v0_system, sizeof(s_meta_v0_system), BLEGATTErrorSuccess); cl_assert_equal_i(ppogatt_client_count(), 0); cl_assert_equal_b(ppogatt_has_client_for_uuid(&s_meta_v0_system.app_uuid), false); } void test_ppogatt__cleanup_client_when_data_subscription_error_response(void) { prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &s_meta_v0_system, sizeof(s_meta_v0_system), BLEGATTErrorSuccess); // Expect subscribe request was made: fake_gatt_client_subscriptions_assert_subscribe(s_characteristics[0][PPoGATTCharacteristicData], BLESubscriptionNotifications, GAPLEClientKernel); // Simulate getting the subscription failure: ppogatt_handle_subscribe(s_characteristics[0][PPoGATTCharacteristicData], BLESubscriptionNotifications, BLEGATTErrorReadNotPermitted); cl_assert_equal_i(ppogatt_client_count(), 0); cl_assert_equal_b(ppogatt_has_client_for_uuid(&s_meta_v0_system.app_uuid), false); } static void prv_discover_and_read_meta_and_reset(void) { prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &s_meta_v0_system, sizeof(s_meta_v0_system), BLEGATTErrorSuccess); // Expect subscribe request was made: fake_gatt_client_subscriptions_assert_subscribe(s_characteristics[0][PPoGATTCharacteristicData], BLESubscriptionNotifications, GAPLEClientKernel); // Simulate getting the subscription confirmation: ppogatt_handle_subscribe(s_characteristics[0][PPoGATTCharacteristicData], BLESubscriptionNotifications, BLEGATTErrorSuccess); // Expect Reset to be initiated ("Reset Request" sent by FW): prv_assert_sent_reset_request(s_characteristics[0][PPoGATTCharacteristicData]); // Session should still no have opened yet: cl_assert_equal_i(fake_comm_session_open_call_count(), 0); } void test_ppogatt__open_session_when_found_pebble_app(void) { prv_discover_and_read_meta_and_reset(); // Simulate getting "Reset Complete" from remote: prv_receive_reset_complete(s_characteristics[0][PPoGATTCharacteristicData]); // Expect "Reset Complete" to be sent by FW: prv_assert_sent_reset_complete(s_characteristics[0][PPoGATTCharacteristicData]); // Expect Session to be opened now: cl_assert_equal_i(fake_comm_session_open_call_count(), 1); } void test_ppogatt__start_reset_upon_out_of_range_ack(void) { test_ppogatt__open_session_when_found_pebble_app(); // Simulate getting an Ack that's outside of the window of outstanding SNs: prv_receive_ack(s_characteristics[0][PPoGATTCharacteristicData], PPOGATT_SN_MOD_DIV / 2); // Expect Reset to be initiated ("Reset Request" sent by FW): prv_assert_sent_reset_request(s_characteristics[0][PPoGATTCharacteristicData]); } void test_ppogatt__ignore_retransmitted_ack(void) { test_ppogatt__o
fake_gatt_client_op_set_read_return_value(BTErrnoOK)
<|repo_name|>pebble <|file_sep|>tests/fw/comm/test_ppogatt.c <|fim_prefix|>d: cl_assert_equal_i(ppogatt_client_count(), 1); Transport *client = ppogatt_client_for_uuid(&metas[i].meta->app_uuid); cl_assert_equal_i(ppogatt_get_destination(client), metas[i].expected_destination); ppogatt_close(client); } } void test_ppogatt__handles_unsupported_meta_ppogatt_version(void) { PPoGATTMetaV0 future_meta_non_compatible = s_meta_v0_system; future_meta_non_compatible.ppogatt_min_version = 0xaa; future_meta_non_compatible.ppogatt_max_version = 0xff; prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &future_meta_non_compatible, sizeof(future_meta_non_compatible), BLEGATTErrorSuccess); // No client created: cl_assert_equal_i(ppogatt_client_count(), 0); cl_assert_equal_b(ppogatt_has_client_for_uuid(&future_meta_non_compatible.app_uuid), false); } void test_ppogatt__handles_invalid_uuid_meta(void) { PPoGATTMetaV0 meta_invalid_uuid = s_meta_v0_system; meta_invalid_uuid.app_uuid = UUID_INVALID; prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &meta_invalid_uuid, sizeof(meta_invalid_uuid), BLEGATTErrorSuccess); // No client created: cl_assert_equal_i(ppogatt_client_count(), 0); cl_assert_equal_b(ppogatt_has_client_for_uuid(&meta_invalid_uuid.app_uuid), false); } void test_ppogatt__deletes_existing_client_after_rediscovery(void) { prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &s_meta_v0_system, sizeof(s_meta_v0_system), BLEGATTErrorSuccess); // Client created: cl_assert_equal_i(ppogatt_client_count(), 1); cl_assert_equal_b(ppogatt_has_client_for_uuid(&s_meta_v0_system.app_uuid), true); Transport *client = ppogatt_client_for_uuid(&s_meta_v0_system.app_uuid); // Rediscovery: ppogatt_invalidate_all_references(); prv_notify_services_discovered(1); // Still one client: cl_assert_equal_i(ppogatt_client_count(), 1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &s_meta_v0_system, sizeof(s_meta_v0_system), BLEGATTErrorSuccess); // Still one client: cl_assert_equal_i(ppogatt_client_count(), 1); cl_assert_equal_b(ppogatt_has_client_for_uuid(&s_meta_v0_system.app_uuid), true); Transport *client2 = ppogatt_client_for_uuid(&s_meta_v0_system.app_uuid); } void test_ppogatt__invalidate_characteristic_refs_immediately_after_update(void) { prv_notify_services_discovered(1); ppogatt_handle_service_removed(&s_characteristics[0][0], PPoGATTCharacteristicNum); const bool can_handle = ppogatt_can_handle_characteristic(s_characteristics[0][PPoGATTCharacteristicData]); cl_assert_equal_b(can_handle, false); } void test_ppogatt__handle_subscribe_to_unknown_characteristic(void) { ppogatt_handle_subscribe(s_unknown_characteristics, BLESubscriptionNotifications, BLEGATTErrorSuccess); // Expect to unsubscribe from the unknown characteristic: fake_gatt_client_subscriptions_assert_subscribe(s_unknown_characteristics, BLESubscriptionNone, GAPLEClientKernel); } void test_ppogatt__cleanup_client_when_meta_read_fails(void) { fake_gatt_client_op_set_read_return_value(BTErrnoInvalidParameter); prv_notify_services_discovered(1); cl_assert_equal_i(ppogatt_client_count(), 0); } void test_ppogatt__cleanup_client_when_meta_read_gets_error_response(void) { <|fim_suffix|>; prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], NULL, 0, BLEGATTErrorInvalidHandle); cl_assert_equal_i(ppogatt_client_count(), 0); } void test_ppogatt__cleanup_client_when_data_subscription_cccd_write_failed(void) { fake_gatt_client_subscriptions_set_subscribe_return_value(BTErrnoInvalidParameter); prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &s_meta_v0_system, sizeof(s_meta_v0_system), BLEGATTErrorSuccess); cl_assert_equal_i(ppogatt_client_count(), 0); cl_assert_equal_b(ppogatt_has_client_for_uuid(&s_meta_v0_system.app_uuid), false); } void test_ppogatt__cleanup_client_when_data_subscription_error_response(void) { prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &s_meta_v0_system, sizeof(s_meta_v0_system), BLEGATTErrorSuccess); // Expect subscribe request was made: fake_gatt_client_subscriptions_assert_subscribe(s_characteristics[0][PPoGATTCharacteristicData], BLESubscriptionNotifications, GAPLEClientKernel); // Simulate getting the subscription failure: ppogatt_handle_subscribe(s_characteristics[0][PPoGATTCharacteristicData], BLESubscriptionNotifications, BLEGATTErrorReadNotPermitted); cl_assert_equal_i(ppogatt_client_count(), 0); cl_assert_equal_b(ppogatt_has_client_for_uuid(&s_meta_v0_system.app_uuid), false); } static void prv_discover_and_read_meta_and_reset(void) { prv_notify_services_discovered(1); ppogatt_handle_read_or_notification(s_characteristics[0][PPoGATTCharacteristicMeta], (const uint8_t *) &s_meta_v0_system, sizeof(s_meta_v0_system), BLEGATTErrorSuccess); // Expect subscribe request was made: fake_gatt_client_subscriptions_assert_subscribe(s_characteristics[0][PPoGATTCharacteristicData], BLESubscriptionNotifications, GAPLEClientKernel); // Simulate getting the subscription confirmation: ppogatt_handle_subscribe(s_characteristics[0][PPoGATTCharacteristicData], BLESubscriptionNotifications, BLEGATTErrorSuccess); // Expect Reset to be initiated ("Reset Request" sent by FW): prv_assert_sent_reset_request(s_characteristics[0][PPoGATTCharacteristicData]); // Session should still no have opened yet: cl_assert_equal_i(fake_comm_session_open_call_count(), 0); } void test_ppogatt__open_session_when_found_pebble_app(void) { prv_discover_and_read_meta_and_reset(); // Simulate getting "Reset Complete" from remote: prv_receive_reset_complete(s_characteristics[0][PPoGATTCharacteristicData]); // Expect "Reset Complete" to be sent by FW: prv_assert_sent_reset_complete(s_characteristics[0][PPoGATTCharacteristicData]); // Expect Session to be opened now: cl_assert_equal_i(fake_comm_session_open_call_count(), 1); } void test_ppogatt__start_reset_upon_out_of_range_ack(void) { test_ppogatt__open_session_when_found_pebble_app(); // Simulate getting an Ack that's outside of the window of outstanding SNs: prv_receive_ack(s_characteristics[0][PPoGATTCharacteristicData], PPOGATT_SN_MOD_DIV / 2); // Expect Reset to be initiated ("Reset Request" sent by FW): prv_assert_sent_reset_request(s_characteristics[0][PPoGATTCharacteristicData]); } void test_ppogatt__ignore_retransmitted_ack(void) { test_ppogatt__o<|fim_middle|>fake_gatt_client_op_set_read_return_value(BTErrnoOK)<|endoftext|>
masked_node
for_statement
src/fw/drivers/stm32f412/qspi.c
= QSPI_ComConfig_ADMode_4Line; modes_bitset |= QSPI_ComConfig_ADSize_24bit; } prv_set_comm_config(modes_bitset, dummy_cycles); if (addr != QSPI_ADDR_NO_ADDR) { QSPI_SetAddress(addr); } } static void prv_indirect_read(QSPIPort *dev, uint8_t instruction, uint32_t addr, uint8_t dummy_cycles, void *buffer, uint32_t length, bool is_ddr) { prv_set_num_data_bytes(length); prv_config_indirect_read(dev, instruction, addr, dummy_cycles, is_ddr); prv_read_bytes(buffer, length); QSPI_ClearFlag(QSPI_FLAG_TC); prv_wait_for_not_busy(); } void qspi_indirect_read_no_addr(QSPIPort *dev, uint8_t instruction, uint8_t dummy_cycles, void *buffer, uint32_t length, bool is_ddr) { prv_indirect_read(dev, instruction, QSPI_ADDR_NO_ADDR, dummy_cycles, buffer, length, is_ddr); } void qspi_indirect_read(QSPIPort *dev, uint8_t instruction, uint32_t addr, uint8_t dummy_cycles, void *buffer, uint32_t length, bool is_ddr) { prv_indirect_read(dev, instruction, addr, dummy_cycles, buffer, length, is_ddr); } void qspi_indirect_read_dma(QSPIPort *dev, uint8_t instruction, uint32_t start_addr, uint8_t dummy_cycles, void *buffer, uint32_t length, bool is_ddr) { // DMA reads are most efficient when doing 32bits at a time. The QSPI bus runs at 100Mhz // and we need to be efficient in handling the data to use it to its full capability. // // So this function is broken into 3 parts: // 1. Do reads 1 byte at a time until buffer_ptr is word-aligned // 2. Do 32-bit DMA transfers for as much as possible // 3. Do reads 1 bytes at a time to deal with non-aligned acceses at the end const uint32_t word_mask = dcache_alignment_mask_minimum(QSPI_DMA_READ_WORD_SIZE); const uintptr_t buffer_address = (uintptr_t)buffer; const uintptr_t last_address = buffer_address + length; const uintptr_t last_address_aligned = last_address & (~word_mask); const uintptr_t start_address_aligned = ((buffer_address + word_mask) & (~word_mask)); uint32_t leading_bytes = start_address_aligned - buffer_address; uint32_t trailing_bytes = last_address - last_address_aligned; uint32_t dma_size = last_address_aligned - start_address_aligned; if (last_address_aligned < start_address_aligned) { dma_size = 0; leading_bytes = length; trailing_bytes = 0; } prv_set_num_data_bytes(length); prv_config_indirect_read(dev, instruction, start_addr, dummy_cycles, is_ddr); if (leading_bytes > 0) { prv_read_bytes(buffer, leading_bytes); } if (dma_size > 0) { // Do 4 bytes at a time for DMA QSPI_SetFIFOThreshold(QSPI_DMA_READ_WORD_SIZE); QSPI_DMACmd(ENABLE); stop_mode_disable(InhibitorFlash); dma_request_start_direct(dev->dma, (void *)start_address_aligned, (void *)&QUADSPI->DR, dma_size, prv_dma_irq_handler, (void *)dev); xSemaphoreTake(dev->state->dma_semaphore, portMAX_DELAY); stop_mode_enable(InhibitorFlash); } if (trailing_bytes > 0) { prv_read_bytes((void *)last_address_aligned, trailing_bytes); } } static void prv_indirect_write(QSPIPort *dev, uint8_t instruction, uint32_t addr, const void *buffer, uint32_t length) { if (length) { PBL_ASSERTN(buffer); prv_set_num_data_bytes(length); } else { PBL_ASSERTN(!buffer); } prv_set_ddr_enabled(false); uint32_t modes_bitset = 0; modes_bitset |= QSPI_ComConfig_FMode_Indirect_Write; modes_bitset |= QSPI_ComConfig_IMode_4Line; modes_bitset |= instruction; if (addr != QSPI_ADDR_NO_ADDR) { modes_bitset |= QSPI_ComConfig_ADMode_4Line; modes_bitset |= QSPI_ComConfig_ADSize_24bit; } if (length) { modes_bitset |= QSPI_ComConfig_DMode_4Line; } prv_set_comm_config(modes_bitset, 0); if (addr != QSPI_ADDR_NO_ADDR) { QSPI_SetAddress(addr); } const uint8_t *read_ptr = buffer;
prv_wait_for_transfer_complete(); QSPI_ClearFlag(QSPI_FLAG_TC); prv_wait_for_not_busy(); } void qspi_indirect_write_no_addr(QSPIPort *dev, uint8_t instruction, const void *buffer, uint32_t length) { prv_indirect_write(dev, instruction, QSPI_ADDR_NO_ADDR, buffer, length); } void qspi_indirect_write(QSPIPort *dev, uint8_t instruction, uint32_t addr, const void *buffer, uint32_t length) { prv_indirect_write(dev, instruction, addr, buffer, length); } void qspi_indirect_write_no_addr_1line(QSPIPort *dev, uint8_t instruction) { prv_set_ddr_enabled(false); uint32_t modes_bitset = 0; modes_bitset |= QSPI_ComConfig_FMode_Indirect_Write; modes_bitset |= QSPI_ComConfig_IMode_1Line; modes_bitset |= instruction; prv_set_comm_config(modes_bitset, 0); prv_wait_for_transfer_complete(); QSPI_ClearFlag(QSPI_FLAG_TC); prv_wait_for_not_busy(); } bool qspi_poll_bit(QSPIPort *dev, uint8_t instruction, uint8_t bit_mask, bool should_be_set, uint32_t timeout_us) { prv_set_num_data_bytes(1); // Set autopolling on the register QSPI_AutoPollingMode_SetInterval(dev->auto_polling_interval); QSPI_AutoPollingMode_Config(should_be_set ? bit_mask : 0, bit_mask, QSPI_PMM_AND); QSPI_AutoPollingModeStopCmd(ENABLE); prv_set_ddr_enabled(false); // Prepare transaction uint32_t modes_bitset = 0; modes_bitset |= QSPI_ComConfig_FMode_Auto_Polling; modes_bitset |= QSPI_ComConfig_DMode_4Line; modes_bitset |= QSPI_ComConfig_IMode_4Line; modes_bitset |= instruction; prv_set_comm_config(modes_bitset, 0); uint32_t loops = 0; while (QSPI_GetFlagStatus(QSPI_FLAG_SM) == RESET) { if ((timeout_us != QSPI_NO_TIMEOUT) && (++loops > timeout_us)) { PBL_LOG(LOG_LEVEL_ERROR, "Timeout waiting for a bit!?!?"); return false; } delay_us(1); } // stop polling mode QSPI_AbortRequest(); prv_wait_for_not_busy(); return true; } void qspi_mmap_start(QSPIPort *dev, uint8_t instruction, uint32_t addr, uint8_t dummy_cycles, uint32_t length, bool is_ddr) { dcache_invalidate((void *)(uintptr_t)(QSPI_MMAP_BASE_ADDRESS + addr), length); prv_set_ddr_enabled(is_ddr); uint32_t modes_bitset = 0; modes_bitset |= is_ddr ? QSPI_ComConfig_DDRMode_Enable : QSPI_ComConfig_DDRMode_Disable; modes_bitset |= is_ddr ? QSPI_ComConfig_DHHC_Enable : QSPI_ComConfig_DHHC_Disable; modes_bitset |= QSPI_ComConfig_FMode_Memory_Mapped; modes_bitset |= QSPI_ComConfig_DMode_4Line; modes_bitset |= QSPI_ComConfig_IMode_4Line; modes_bitset |= QSPI_ComConfig_ADMode_4Line; modes_bitset |= QSPI_ComConfig_ADSize_24bit; modes_bitset |= instruction; prv_set_comm_config(modes_bitset, dummy_cycles); // The QSPI will prefetch bytes as long as nCS is low. This causes the flash part to draw a lot // more power (10mA vs 10uA in the case of Silk). Set the timeout such that the prefetch will // stop after 10 clock cycles of inactivity. QSPI_MemoryMappedMode_SetTimeout(10); // HACK ALERT: It seems like the MCU may send the wrong address for the first MMAP after certain // flash operations (we have seen it with an indirect read). To work around this, kick off one // read sufficiently far away from the area we want to read. This seems to reset the QSPI // controller back into a good state. This workaround is a little wasteful as it kicks off a 32 // byte flash read but at 50MHz that should only take ~1.5us: // ((1byte +3byteaddr + 32bytes data) * 2 clocks/byte + 4 dummy_clocks) / 50Mhz = 1.52us volatile uint8_t *qspi_wa_addr = (uint8_t *)(QSPI_MMAP_BASE_ADDRESS + ((addr > 128) ? 0 : 256)); dcache_invalidate((void *)qspi_wa_addr, 1); (void)*qspi_wa_addr; } void qspi_mmap_stop(QSPIPort *dev) { QSPI_AbortRequest(); prv_wait_for_not_busy(); }
for (uint32_t i = 0; i < length; ++i) { // Note: this will stall the CPU when the FIFO gets full while data is being sent. // For performance reasons, we should replace it with DMA in the future // PBL-28805 QSPI_SendData8(read_ptr[i]); }
<|repo_name|>pebble <|file_sep|>src/fw/drivers/stm32f412/qspi.c <|fim_prefix|>= QSPI_ComConfig_ADMode_4Line; modes_bitset |= QSPI_ComConfig_ADSize_24bit; } prv_set_comm_config(modes_bitset, dummy_cycles); if (addr != QSPI_ADDR_NO_ADDR) { QSPI_SetAddress(addr); } } static void prv_indirect_read(QSPIPort *dev, uint8_t instruction, uint32_t addr, uint8_t dummy_cycles, void *buffer, uint32_t length, bool is_ddr) { prv_set_num_data_bytes(length); prv_config_indirect_read(dev, instruction, addr, dummy_cycles, is_ddr); prv_read_bytes(buffer, length); QSPI_ClearFlag(QSPI_FLAG_TC); prv_wait_for_not_busy(); } void qspi_indirect_read_no_addr(QSPIPort *dev, uint8_t instruction, uint8_t dummy_cycles, void *buffer, uint32_t length, bool is_ddr) { prv_indirect_read(dev, instruction, QSPI_ADDR_NO_ADDR, dummy_cycles, buffer, length, is_ddr); } void qspi_indirect_read(QSPIPort *dev, uint8_t instruction, uint32_t addr, uint8_t dummy_cycles, void *buffer, uint32_t length, bool is_ddr) { prv_indirect_read(dev, instruction, addr, dummy_cycles, buffer, length, is_ddr); } void qspi_indirect_read_dma(QSPIPort *dev, uint8_t instruction, uint32_t start_addr, uint8_t dummy_cycles, void *buffer, uint32_t length, bool is_ddr) { // DMA reads are most efficient when doing 32bits at a time. The QSPI bus runs at 100Mhz // and we need to be efficient in handling the data to use it to its full capability. // // So this function is broken into 3 parts: // 1. Do reads 1 byte at a time until buffer_ptr is word-aligned // 2. Do 32-bit DMA transfers for as much as possible // 3. Do reads 1 bytes at a time to deal with non-aligned acceses at the end const uint32_t word_mask = dcache_alignment_mask_minimum(QSPI_DMA_READ_WORD_SIZE); const uintptr_t buffer_address = (uintptr_t)buffer; const uintptr_t last_address = buffer_address + length; const uintptr_t last_address_aligned = last_address & (~word_mask); const uintptr_t start_address_aligned = ((buffer_address + word_mask) & (~word_mask)); uint32_t leading_bytes = start_address_aligned - buffer_address; uint32_t trailing_bytes = last_address - last_address_aligned; uint32_t dma_size = last_address_aligned - start_address_aligned; if (last_address_aligned < start_address_aligned) { dma_size = 0; leading_bytes = length; trailing_bytes = 0; } prv_set_num_data_bytes(length); prv_config_indirect_read(dev, instruction, start_addr, dummy_cycles, is_ddr); if (leading_bytes > 0) { prv_read_bytes(buffer, leading_bytes); } if (dma_size > 0) { // Do 4 bytes at a time for DMA QSPI_SetFIFOThreshold(QSPI_DMA_READ_WORD_SIZE); QSPI_DMACmd(ENABLE); stop_mode_disable(InhibitorFlash); dma_request_start_direct(dev->dma, (void *)start_address_aligned, (void *)&QUADSPI->DR, dma_size, prv_dma_irq_handler, (void *)dev); xSemaphoreTake(dev->state->dma_semaphore, portMAX_DELAY); stop_mode_enable(InhibitorFlash); } if (trailing_bytes > 0) { prv_read_bytes((void *)last_address_aligned, trailing_bytes); } } static void prv_indirect_write(QSPIPort *dev, uint8_t instruction, uint32_t addr, const void *buffer, uint32_t length) { if (length) { PBL_ASSERTN(buffer); prv_set_num_data_bytes(length); } else { PBL_ASSERTN(!buffer); } prv_set_ddr_enabled(false); uint32_t modes_bitset = 0; modes_bitset |= QSPI_ComConfig_FMode_Indirect_Write; modes_bitset |= QSPI_ComConfig_IMode_4Line; modes_bitset |= instruction; if (addr != QSPI_ADDR_NO_ADDR) { modes_bitset |= QSPI_ComConfig_ADMode_4Line; modes_bitset |= QSPI_ComConfig_ADSize_24bit; } if (length) { modes_bitset |= QSPI_ComConfig_DMode_4Line; } prv_set_comm_config(modes_bitset, 0); if (addr != QSPI_ADDR_NO_ADDR) { QSPI_SetAddress(addr); } const uint8_t *read_ptr = buffer; <|fim_suffix|> prv_wait_for_transfer_complete(); QSPI_ClearFlag(QSPI_FLAG_TC); prv_wait_for_not_busy(); } void qspi_indirect_write_no_addr(QSPIPort *dev, uint8_t instruction, const void *buffer, uint32_t length) { prv_indirect_write(dev, instruction, QSPI_ADDR_NO_ADDR, buffer, length); } void qspi_indirect_write(QSPIPort *dev, uint8_t instruction, uint32_t addr, const void *buffer, uint32_t length) { prv_indirect_write(dev, instruction, addr, buffer, length); } void qspi_indirect_write_no_addr_1line(QSPIPort *dev, uint8_t instruction) { prv_set_ddr_enabled(false); uint32_t modes_bitset = 0; modes_bitset |= QSPI_ComConfig_FMode_Indirect_Write; modes_bitset |= QSPI_ComConfig_IMode_1Line; modes_bitset |= instruction; prv_set_comm_config(modes_bitset, 0); prv_wait_for_transfer_complete(); QSPI_ClearFlag(QSPI_FLAG_TC); prv_wait_for_not_busy(); } bool qspi_poll_bit(QSPIPort *dev, uint8_t instruction, uint8_t bit_mask, bool should_be_set, uint32_t timeout_us) { prv_set_num_data_bytes(1); // Set autopolling on the register QSPI_AutoPollingMode_SetInterval(dev->auto_polling_interval); QSPI_AutoPollingMode_Config(should_be_set ? bit_mask : 0, bit_mask, QSPI_PMM_AND); QSPI_AutoPollingModeStopCmd(ENABLE); prv_set_ddr_enabled(false); // Prepare transaction uint32_t modes_bitset = 0; modes_bitset |= QSPI_ComConfig_FMode_Auto_Polling; modes_bitset |= QSPI_ComConfig_DMode_4Line; modes_bitset |= QSPI_ComConfig_IMode_4Line; modes_bitset |= instruction; prv_set_comm_config(modes_bitset, 0); uint32_t loops = 0; while (QSPI_GetFlagStatus(QSPI_FLAG_SM) == RESET) { if ((timeout_us != QSPI_NO_TIMEOUT) && (++loops > timeout_us)) { PBL_LOG(LOG_LEVEL_ERROR, "Timeout waiting for a bit!?!?"); return false; } delay_us(1); } // stop polling mode QSPI_AbortRequest(); prv_wait_for_not_busy(); return true; } void qspi_mmap_start(QSPIPort *dev, uint8_t instruction, uint32_t addr, uint8_t dummy_cycles, uint32_t length, bool is_ddr) { dcache_invalidate((void *)(uintptr_t)(QSPI_MMAP_BASE_ADDRESS + addr), length); prv_set_ddr_enabled(is_ddr); uint32_t modes_bitset = 0; modes_bitset |= is_ddr ? QSPI_ComConfig_DDRMode_Enable : QSPI_ComConfig_DDRMode_Disable; modes_bitset |= is_ddr ? QSPI_ComConfig_DHHC_Enable : QSPI_ComConfig_DHHC_Disable; modes_bitset |= QSPI_ComConfig_FMode_Memory_Mapped; modes_bitset |= QSPI_ComConfig_DMode_4Line; modes_bitset |= QSPI_ComConfig_IMode_4Line; modes_bitset |= QSPI_ComConfig_ADMode_4Line; modes_bitset |= QSPI_ComConfig_ADSize_24bit; modes_bitset |= instruction; prv_set_comm_config(modes_bitset, dummy_cycles); // The QSPI will prefetch bytes as long as nCS is low. This causes the flash part to draw a lot // more power (10mA vs 10uA in the case of Silk). Set the timeout such that the prefetch will // stop after 10 clock cycles of inactivity. QSPI_MemoryMappedMode_SetTimeout(10); // HACK ALERT: It seems like the MCU may send the wrong address for the first MMAP after certain // flash operations (we have seen it with an indirect read). To work around this, kick off one // read sufficiently far away from the area we want to read. This seems to reset the QSPI // controller back into a good state. This workaround is a little wasteful as it kicks off a 32 // byte flash read but at 50MHz that should only take ~1.5us: // ((1byte +3byteaddr + 32bytes data) * 2 clocks/byte + 4 dummy_clocks) / 50Mhz = 1.52us volatile uint8_t *qspi_wa_addr = (uint8_t *)(QSPI_MMAP_BASE_ADDRESS + ((addr > 128) ? 0 : 256)); dcache_invalidate((void *)qspi_wa_addr, 1); (void)*qspi_wa_addr; } void qspi_mmap_stop(QSPIPort *dev) { QSPI_AbortRequest(); prv_wait_for_not_busy(); } <|fim_middle|>for (uint32_t i = 0; i < length; ++i) { // Note: this will stall the CPU when the FIFO gets full while data is being sent. // For performance reasons, we should replace it with DMA in the future // PBL-28805 QSPI_SendData8(read_ptr[i]); }<|endoftext|>
masked_node
call_expression
src/fw/services/normal/notifications/do_not_disturb.c
? WeekendSchedule : WeekdaySchedule); } // Updates the timer for scheduled DND check // Only enters if at least one of the schedules is enabled static void prv_set_schedule_mode_timer() { struct tm time; rtc_get_time_tm(&time); DoNotDisturbScheduleType curr_schedule_type = prv_current_schedule_type(); DoNotDisturbSchedule curr_schedule; do_not_disturb_get_schedule(curr_schedule_type, &curr_schedule); bool curr_schedule_enabled = do_not_disturb_is_schedule_enabled(curr_schedule_type); time_t seconds_until_update; bool is_enable_next; int curr_day = time.tm_wday; if (!curr_schedule_enabled) { // Only next schedule is enabled is_enable_next = true; // Depending on the current schedule, determine the first day index of the next schedule int next_schedule_day = (curr_schedule_type == WeekdaySchedule) ? Saturday : Monday; // Count the number of full days until next schedule (Sunday = 0) int num_full_days = ((next_schedule_day - curr_day + DAYS_PER_WEEK) % DAYS_PER_WEEK) - 1; // Calculate the number of seconds until the start of the next schedule, update then seconds_until_update = time_util_get_seconds_until_daily_time(&time, 0, 0) + (num_full_days * SECONDS_PER_DAY); } else { // Current schedule is enabled const time_t seconds_until_start = time_util_get_seconds_until_daily_time( &time, curr_schedule.from_hour, curr_schedule.from_minute); const time_t seconds_until_end = time_util_get_seconds_until_daily_time( &time, curr_schedule.to_hour, curr_schedule.to_minute); seconds_until_update = MIN(seconds_until_start, seconds_until_end); is_enable_next = (seconds_until_update == seconds_until_start); // Update at midnight if on the last day of the current schedule if ((curr_day == Sunday) || (curr_day == Friday)) { const time_t seconds_until_midnight = time_util_get_seconds_until_daily_time(&time, 0, 0); seconds_until_update = MIN(seconds_until_update, seconds_until_midnight); } } if (s_data.is_in_schedule_period == is_enable_next) { // Coming out of scheduled DND with manual DND on, turning it off if (is_enable_next && do_not_disturb_is_manually_enabled()) { do_not_disturb_set_manually_enabled(false); } s_data.is_in_schedule_period = !is_enable_next; } PBL_LOG(LOG_LEVEL_INFO, "%s scheduled period. %u seconds until update", s_data.is_in_schedule_period ? "In" : "Out of", (unsigned int) seconds_until_update); bool success = new_timer_start(s_data.update_timer_id, seconds_until_update * 1000, prv_update_schedule_mode_timer_callback, NULL, 0 /*flags*/); PBL_ASSERTN(success); } static bool prv_is_current_schedule_enabled() { return (do_not_disturb_is_schedule_enabled(prv_current_schedule_type())); } static bool prv_is_schedule_active(void) { return (prv_is_current_schedule_enabled() && s_data.is_in_schedule_period && !s_data.manually_override_dnd); } static bool prv_is_smart_dnd_active(void) { return (calendar_event_is_ongoing() && do_not_disturb_is_smart_dnd_enabled() && !s_data.manually_override_dnd); } /////////////////////////////////////////////////////////////////////////////////////////////////// //! Public Functions /////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SYSCALL(bool, sys_do_not_disturb_is_active, void) { return do_not_disturb_is_active(); } bool do_not_disturb_is_active(void) { if (do_not_disturb_is_manually_enabled() || prv_is_schedule_active() || prv_is_smart_dnd_active()) { return true; } return false; } bool do_not_disturb_is_manually_enabled(void) { return alerts_preferences_dnd_is_manually_enabled(); } void do_not_disturb_set_manually_enabled(bool enable) { const bool is_auto_dnd = prv_is_current_schedule_enabled() || do_not_disturb_is_smart_dnd_enabled(); const bool was_active = do_not_disturb_is_active();
; // Turning the manual DND OFF in an active DND mode overrides the automatic mode if (!enable && was_active && is_auto_dnd) { s_data.manually_override_dnd = true; } prv_do_update(); } void do_not_disturb_toggle_manually_enabled(ManualDNDFirstUseSource source) { FirstUseSource first_use_source = (FirstUseSource)source; if (!alerts_preferences_check_and_set_first_use_complete(first_use_source)) { prv_push_manual_dnd_first_use_dialog(source); } else { if (source == ManualDNDFirstUseSourceSettingsMenu) { prv_toggle_manual_dnd_from_settings_menu(NULL); } else { prv_toggle_manual_dnd_from_action_menu(NULL); } } } bool do_not_disturb_is_smart_dnd_enabled(void) { return alerts_preferences_dnd_is_smart_enabled(); } void do_not_disturb_toggle_smart_dnd(void) { if (!alerts_preferences_check_and_set_first_use_complete(FirstUseSourceSmartDND)) { prv_push_smart_dnd_first_use_dialog(); } else { prv_toggle_smart_dnd(NULL); } } void do_not_disturb_get_schedule(DoNotDisturbScheduleType type, DoNotDisturbSchedule *schedule_out) { alerts_preferences_dnd_get_schedule(type, schedule_out); } void do_not_disturb_set_schedule(DoNotDisturbScheduleType type, DoNotDisturbSchedule *schedule) { alerts_preferences_dnd_set_schedule(type, schedule); prv_try_update_schedule_mode_callback(true); } bool do_not_disturb_is_schedule_enabled(DoNotDisturbScheduleType type) { return alerts_preferences_dnd_is_schedule_enabled(type); } void do_not_disturb_set_schedule_enabled(DoNotDisturbScheduleType type, bool scheduled) { alerts_preferences_dnd_set_schedule_enabled(type, scheduled); prv_try_update_schedule_mode_callback(true); } void do_not_disturb_toggle_scheduled(DoNotDisturbScheduleType type) { alerts_preferences_dnd_set_schedule_enabled(type, !alerts_preferences_dnd_is_schedule_enabled(type)); prv_try_update_schedule_mode_callback(true); } void do_not_disturb_init(void) { s_data = (DoNotDisturbData) { .update_timer_id = new_timer_create(), .was_active = false, }; prv_try_update_schedule_mode((void*) true); } void do_not_disturb_handle_clock_change(void) { prv_try_update_schedule_mode_callback(false); } void do_not_disturb_handle_calendar_event(PebbleCalendarEvent *e) { prv_do_update(); } void do_not_disturb_manual_toggle_with_dialog(void) { do_not_disturb_toggle_push(ActionTogglePrompt_Auto, false /* set_exit_reason */); } #ifdef UNITTEST TimerID get_dnd_timer_id(void) { return s_data.update_timer_id; } void set_dnd_timer_id(TimerID id) { s_data.update_timer_id = id; } #endif
alerts_preferences_dnd_set_manually_enabled(enable)
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/notifications/do_not_disturb.c <|fim_prefix|> ? WeekendSchedule : WeekdaySchedule); } // Updates the timer for scheduled DND check // Only enters if at least one of the schedules is enabled static void prv_set_schedule_mode_timer() { struct tm time; rtc_get_time_tm(&time); DoNotDisturbScheduleType curr_schedule_type = prv_current_schedule_type(); DoNotDisturbSchedule curr_schedule; do_not_disturb_get_schedule(curr_schedule_type, &curr_schedule); bool curr_schedule_enabled = do_not_disturb_is_schedule_enabled(curr_schedule_type); time_t seconds_until_update; bool is_enable_next; int curr_day = time.tm_wday; if (!curr_schedule_enabled) { // Only next schedule is enabled is_enable_next = true; // Depending on the current schedule, determine the first day index of the next schedule int next_schedule_day = (curr_schedule_type == WeekdaySchedule) ? Saturday : Monday; // Count the number of full days until next schedule (Sunday = 0) int num_full_days = ((next_schedule_day - curr_day + DAYS_PER_WEEK) % DAYS_PER_WEEK) - 1; // Calculate the number of seconds until the start of the next schedule, update then seconds_until_update = time_util_get_seconds_until_daily_time(&time, 0, 0) + (num_full_days * SECONDS_PER_DAY); } else { // Current schedule is enabled const time_t seconds_until_start = time_util_get_seconds_until_daily_time( &time, curr_schedule.from_hour, curr_schedule.from_minute); const time_t seconds_until_end = time_util_get_seconds_until_daily_time( &time, curr_schedule.to_hour, curr_schedule.to_minute); seconds_until_update = MIN(seconds_until_start, seconds_until_end); is_enable_next = (seconds_until_update == seconds_until_start); // Update at midnight if on the last day of the current schedule if ((curr_day == Sunday) || (curr_day == Friday)) { const time_t seconds_until_midnight = time_util_get_seconds_until_daily_time(&time, 0, 0); seconds_until_update = MIN(seconds_until_update, seconds_until_midnight); } } if (s_data.is_in_schedule_period == is_enable_next) { // Coming out of scheduled DND with manual DND on, turning it off if (is_enable_next && do_not_disturb_is_manually_enabled()) { do_not_disturb_set_manually_enabled(false); } s_data.is_in_schedule_period = !is_enable_next; } PBL_LOG(LOG_LEVEL_INFO, "%s scheduled period. %u seconds until update", s_data.is_in_schedule_period ? "In" : "Out of", (unsigned int) seconds_until_update); bool success = new_timer_start(s_data.update_timer_id, seconds_until_update * 1000, prv_update_schedule_mode_timer_callback, NULL, 0 /*flags*/); PBL_ASSERTN(success); } static bool prv_is_current_schedule_enabled() { return (do_not_disturb_is_schedule_enabled(prv_current_schedule_type())); } static bool prv_is_schedule_active(void) { return (prv_is_current_schedule_enabled() && s_data.is_in_schedule_period && !s_data.manually_override_dnd); } static bool prv_is_smart_dnd_active(void) { return (calendar_event_is_ongoing() && do_not_disturb_is_smart_dnd_enabled() && !s_data.manually_override_dnd); } /////////////////////////////////////////////////////////////////////////////////////////////////// //! Public Functions /////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SYSCALL(bool, sys_do_not_disturb_is_active, void) { return do_not_disturb_is_active(); } bool do_not_disturb_is_active(void) { if (do_not_disturb_is_manually_enabled() || prv_is_schedule_active() || prv_is_smart_dnd_active()) { return true; } return false; } bool do_not_disturb_is_manually_enabled(void) { return alerts_preferences_dnd_is_manually_enabled(); } void do_not_disturb_set_manually_enabled(bool enable) { const bool is_auto_dnd = prv_is_current_schedule_enabled() || do_not_disturb_is_smart_dnd_enabled(); const bool was_active = do_not_disturb_is_active(); <|fim_suffix|>; // Turning the manual DND OFF in an active DND mode overrides the automatic mode if (!enable && was_active && is_auto_dnd) { s_data.manually_override_dnd = true; } prv_do_update(); } void do_not_disturb_toggle_manually_enabled(ManualDNDFirstUseSource source) { FirstUseSource first_use_source = (FirstUseSource)source; if (!alerts_preferences_check_and_set_first_use_complete(first_use_source)) { prv_push_manual_dnd_first_use_dialog(source); } else { if (source == ManualDNDFirstUseSourceSettingsMenu) { prv_toggle_manual_dnd_from_settings_menu(NULL); } else { prv_toggle_manual_dnd_from_action_menu(NULL); } } } bool do_not_disturb_is_smart_dnd_enabled(void) { return alerts_preferences_dnd_is_smart_enabled(); } void do_not_disturb_toggle_smart_dnd(void) { if (!alerts_preferences_check_and_set_first_use_complete(FirstUseSourceSmartDND)) { prv_push_smart_dnd_first_use_dialog(); } else { prv_toggle_smart_dnd(NULL); } } void do_not_disturb_get_schedule(DoNotDisturbScheduleType type, DoNotDisturbSchedule *schedule_out) { alerts_preferences_dnd_get_schedule(type, schedule_out); } void do_not_disturb_set_schedule(DoNotDisturbScheduleType type, DoNotDisturbSchedule *schedule) { alerts_preferences_dnd_set_schedule(type, schedule); prv_try_update_schedule_mode_callback(true); } bool do_not_disturb_is_schedule_enabled(DoNotDisturbScheduleType type) { return alerts_preferences_dnd_is_schedule_enabled(type); } void do_not_disturb_set_schedule_enabled(DoNotDisturbScheduleType type, bool scheduled) { alerts_preferences_dnd_set_schedule_enabled(type, scheduled); prv_try_update_schedule_mode_callback(true); } void do_not_disturb_toggle_scheduled(DoNotDisturbScheduleType type) { alerts_preferences_dnd_set_schedule_enabled(type, !alerts_preferences_dnd_is_schedule_enabled(type)); prv_try_update_schedule_mode_callback(true); } void do_not_disturb_init(void) { s_data = (DoNotDisturbData) { .update_timer_id = new_timer_create(), .was_active = false, }; prv_try_update_schedule_mode((void*) true); } void do_not_disturb_handle_clock_change(void) { prv_try_update_schedule_mode_callback(false); } void do_not_disturb_handle_calendar_event(PebbleCalendarEvent *e) { prv_do_update(); } void do_not_disturb_manual_toggle_with_dialog(void) { do_not_disturb_toggle_push(ActionTogglePrompt_Auto, false /* set_exit_reason */); } #ifdef UNITTEST TimerID get_dnd_timer_id(void) { return s_data.update_timer_id; } void set_dnd_timer_id(TimerID id) { s_data.update_timer_id = id; } #endif <|fim_middle|>alerts_preferences_dnd_set_manually_enabled(enable)<|endoftext|>
masked_node
call_expression
tools/clar/clar_sandbox.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> static char _clar_path[4096]; static int is_valid_tmp_path(const char *path) { STAT_T st; if (stat(path, &st) != 0) return 0; if (!S_ISDIR(st.st_mode)) return 0; return (access(path, W_OK) == 0); } static int find_tmp_path(char *buffer, size_t length) { #ifndef _WIN32 static const size_t var_count = 4; static const char *env_vars[] = { "TMPDIR", "TMP", "TEMP", "USERPROFILE" }; size_t i; for (i = 0; i < var_count; ++i) { const char *env = getenv(env_vars[i]); if (!env) continue; if (
) { strncpy(buffer, env, length); return 0; } } /* If the environment doesn't say anything, try to use /tmp */ if (is_valid_tmp_path("/tmp")) { strncpy(buffer, "/tmp", length); return 0; } #else if (GetTempPath((DWORD)length, buffer)) return 0; #endif /* This system doesn't like us, try to use the current directory */ if (is_valid_tmp_path(".")) { strncpy(buffer, ".", length); return 0; } return -1; } static void clar_unsandbox(void) { if (_clar_path[0] == '\0') return; #ifdef _WIN32 chdir(".."); #endif fs_rm(_clar_path); } char *mkdtemp(char *template); static int build_sandbox_path(void) { const char path_tail[] = "clar_tmp_XXXXXX"; size_t len; if (find_tmp_path(_clar_path, sizeof(_clar_path)) < 0) return -1; len = strlen(_clar_path); #ifdef _WIN32 { /* normalize path to POSIX forward slashes */ size_t i; for (i = 0; i < len; ++i) { if (_clar_path[i] == '\\') _clar_path[i] = '/'; } } #endif if (_clar_path[len - 1] != '/') { _clar_path[len++] = '/'; } strncpy(_clar_path + len, path_tail, sizeof(_clar_path) - len); #if defined(__MINGW32__) if (_mktemp(_clar_path) == NULL) return -1; if (mkdir(_clar_path, 0700) != 0) return -1; #elif defined(_WIN32) if (_mktemp_s(_clar_path, sizeof(_clar_path)) != 0) return -1; if (mkdir(_clar_path, 0700) != 0) return -1; #else if (mkdtemp(_clar_path) == NULL) return -1; #endif return 0; } static int clar_sandbox(void) { if (_clar_path[0] == '\0' && build_sandbox_path() < 0) return -1; if (chdir(_clar_path) != 0) return -1; return 0; }
is_valid_tmp_path(env)
<|repo_name|>pebble <|file_sep|>tools/clar/clar_sandbox.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> static char _clar_path[4096]; static int is_valid_tmp_path(const char *path) { STAT_T st; if (stat(path, &st) != 0) return 0; if (!S_ISDIR(st.st_mode)) return 0; return (access(path, W_OK) == 0); } static int find_tmp_path(char *buffer, size_t length) { #ifndef _WIN32 static const size_t var_count = 4; static const char *env_vars[] = { "TMPDIR", "TMP", "TEMP", "USERPROFILE" }; size_t i; for (i = 0; i < var_count; ++i) { const char *env = getenv(env_vars[i]); if (!env) continue; if (<|fim_suffix|>) { strncpy(buffer, env, length); return 0; } } /* If the environment doesn't say anything, try to use /tmp */ if (is_valid_tmp_path("/tmp")) { strncpy(buffer, "/tmp", length); return 0; } #else if (GetTempPath((DWORD)length, buffer)) return 0; #endif /* This system doesn't like us, try to use the current directory */ if (is_valid_tmp_path(".")) { strncpy(buffer, ".", length); return 0; } return -1; } static void clar_unsandbox(void) { if (_clar_path[0] == '\0') return; #ifdef _WIN32 chdir(".."); #endif fs_rm(_clar_path); } char *mkdtemp(char *template); static int build_sandbox_path(void) { const char path_tail[] = "clar_tmp_XXXXXX"; size_t len; if (find_tmp_path(_clar_path, sizeof(_clar_path)) < 0) return -1; len = strlen(_clar_path); #ifdef _WIN32 { /* normalize path to POSIX forward slashes */ size_t i; for (i = 0; i < len; ++i) { if (_clar_path[i] == '\\') _clar_path[i] = '/'; } } #endif if (_clar_path[len - 1] != '/') { _clar_path[len++] = '/'; } strncpy(_clar_path + len, path_tail, sizeof(_clar_path) - len); #if defined(__MINGW32__) if (_mktemp(_clar_path) == NULL) return -1; if (mkdir(_clar_path, 0700) != 0) return -1; #elif defined(_WIN32) if (_mktemp_s(_clar_path, sizeof(_clar_path)) != 0) return -1; if (mkdir(_clar_path, 0700) != 0) return -1; #else if (mkdtemp(_clar_path) == NULL) return -1; #endif return 0; } static int clar_sandbox(void) { if (_clar_path[0] == '\0' && build_sandbox_path() < 0) return -1; if (chdir(_clar_path) != 0) return -1; return 0; } <|fim_middle|>is_valid_tmp_path(env)<|endoftext|>
masked_node
call_expression
src/fw/applib/rockyjs/api/rocky_api_graphics.c
ssions and * limitations under the License. */ #include "jerry-api.h" #include "rocky_api_graphics.h" #include "rocky_api_graphics_path2d.h" #include "rocky_api_graphics_text.h" #include "rocky_api_util.h" #include "rocky_api_util_args.h" #include "applib/app.h" #include "applib/app_logging.h" #include "applib/ui/ui.h" #include "kernel/pbl_malloc.h" #include "system/logging.h" #include "system/passert.h" #include "util/attributes.h" #include "util/size.h" #include "util/trig.h" #include "process_state/app_state/app_state.h" #include "rocky_api_errors.h" #include "rocky_api_global.h" #include "rocky_api_graphics_color.h" #define ROCKY_EVENT_DRAW "draw" #define ROCKY_EVENT_DRAW_CONTEXT "context" #define ROCKY_REQUESTDRAW "requestDraw" #define ROCKY_CONTEXT2D_CONSTRUCTOR "CanvasRenderingContext2D" #define ROCKY_CONTEXT2D_CANVAS "canvas" #define ROCKY_CONTEXT2D_CLEARRECT "clearRect" #define ROCKY_CONTEXT2D_FILLRECT "fillRect" #define ROCKY_CONTEXT2D_FILLRADIAL "rockyFillRadial" #define ROCKY_CONTEXT2D_STROKERECT "strokeRect" #define ROCKY_CONTEXT2D_LINEWIDTH "lineWidth" #define ROCKY_CONTEXT2D_STROKESTYLE "strokeStyle" #define ROCKY_CONTEXT2D_FILLSTYLE "fillStyle" #define ROCKY_CONTEXT2D_SAVE "save" #define ROCKY_CONTEXT2D_RESTORE "restore" #define ROCKY_CANVAS_CONSTRUCTOR "CanvasElement" #define ROCKY_CANVAS_CLIENTWIDTH "clientWidth" #define ROCKY_CANVAS_CLIENTHEIGHT "clientHeight" #define ROCKY_CANVAS_UNOBSTRUCTEDLEFT "unobstructedLeft" #define ROCKY_CANVAS_UNOBSTRUCTEDTOP "unobstructedTop" #define ROCKY_CANVAS_UNOBSTRUCTEDWIDTH "unobstructedWidth" #define ROCKY_CANVAS_UNOBSTRUCTEDHEIGHT "unobstructedHeight" typedef struct { ListNode node; GDrawState draw_state; } Context2DStoredState; // TODO: PBL-35780 make this part of app_state_get_rocky_runtime_context() SECTION(".rocky_bss") static Context2DStoredState *s_canvas_context_2d_stored_states; T_STATIC jerry_value_t prv_create_canvas_context_2d_for_layer(Layer *layer) { JS_VAR context_2d = rocky_create_with_constructor(ROCKY_CONTEXT2D_CONSTRUCTOR, /* no args: */ NULL, 0); JS_VAR canvas = jerry_get_object_field(context_2d, ROCKY_CONTEXT2D_CANVAS); { JS_VAR client_width = jerry_create_number(layer->bounds.size.w); JS_VAR client_height = jerry_create_number(layer->bounds.size.h); jerry_set_object_field(canvas, ROCKY_CANVAS_CLIENTWIDTH, client_width); jerry_set_object_field(canvas, ROCKY_CANVAS_CLIENTHEIGHT, client_height); } { GRect uo_rect; layer_get_unobstructed_bounds(layer, &uo_rect); JS_VAR unobstructed_left = jerry_create_number(uo_rect.origin.x); JS_VAR unobstructed_right = jerry_create_number(uo_rect.origin.y); JS_VAR unobstructed_width = jerry_create_number(uo_rect.size.w); JS_VAR unobstructed_height = jerry_create_number(uo_rect.size.h); jerry_set_object_field(canvas, ROCKY_CANVAS_UNOBSTRUCTEDLEFT, unobstructed_left); jerry_set_object_field(canvas, ROCKY_CANVAS_UNOBSTRUCTEDTOP, unobstructed_right); jerry_set_object_field(canvas, ROCKY_CANVAS_UNOBSTRUCTEDWIDTH, unobstructed_width); jerry_set_object_field(canvas, ROCKY_CANVAS_UNOBSTRUCTEDHEIGHT, unobstructed_height); } return jerry_acquire_value(context_2d); } static void prv_rocky_update_proc(Layer *layer, GContext *ctx) { if (!rocky_global_has_event_handlers(ROCKY_EVENT_DRAW)) { return; } rocky_api_graphics_text_reset_state(); rocky_api_graphics_path2d_reset_state(); JS_VAR event = rocky_global_create_event(ROCKY_EVENT_DRAW); JS_VAR context_2d = prv_create_canvas_context_2d_for_layer(layer); jerry_set_object_field(event, ROCKY_EVENT_DRAW_CONTEXT, context_2d); rocky_global_call_event_handlers(event); rocky_api_graphics_path2d_reset_state(); } JERRY_FUNCTION(prv_request_draw) { Window *const top_window = app_window_stack_get_top_window(); if (!top_window) { return jerry_create_undefined(); } layer_mark_dirty(&top_window->layer); return jerry_create_undefined(); } GContext *rocky_api_graphics_get_gcontext(void) { return
; } static jerry_value_t prv_rect_precise_call(const jerry_length_t argc, const jerry_value_t argv[], void (*func)(GContext *, const GRectPrecise *)) { GRectPrecise rect; ROCKY_ARGS_ASSIGN_OR_RETURN_ERROR(ROCKY_ARG(rect)); GContext *const ctx = rocky_api_graphics_get_gcontext(); func(ctx, &rect); return jerry_create_undefined(); } static GRect prv_grect_from_precise(const GRectPrecise *rect) { const int16_t x = Fixed_S16_3_rounded_int(rect->origin.x); const int16_t y = Fixed_S16_3_rounded_int(rect->origin.y); const int16_t w = Fixed_S16_3_rounded_int(grect_precise_get_max_x(rect)) - x; const int16_t h = Fixed_S16_3_rounded_int(grect_precise_get_max_y(rect)) - y; return GRect(x, y, w, h); } static jerry_value_t prv_rect_call(const jerry_length_t argc, const jerry_value_t argv[], void (*func)(GContext *, const GRect *)) { GRectPrecise prect; ROCKY_ARGS_ASSIGN_OR_RETURN_ERROR( ROCKY_ARG(prect), ); GContext *const ctx = rocky_api_graphics_get_gcontext(); const GRect rect = prv_grect_from_precise(&prect); func(ctx, &rect); return jerry_create_undefined(); } JERRY_FUNCTION(prv_fill_rect) { return prv_rect_call(argc, argv, graphics_fill_rect); } static void prv_draw_rect_impl(GContext *ctx, const GRectPrecise *rect) { GRectPrecise adjusted_rect = *rect; adjusted_rect.origin.x.raw_value -= FIXED_S16_3_HALF.raw_value; adjusted_rect.origin.y.raw_value -= FIXED_S16_3_HALF.raw_value; graphics_draw_rect_precise(ctx, &adjusted_rect); } JERRY_FUNCTION(prv_stroke_rect) { return prv_rect_precise_call(argc, argv, prv_draw_rect_impl); } JERRY_FUNCTION(prv_clear_rect) { GContext *const ctx = rocky_api_graphics_get_gcontext(); const GColor prev_color = ctx->draw_state.fill_color; ctx->draw_state.fill_color = GColorBlack; JS_VAR result = prv_rect_call(argc, argv, graphics_fill_rect); ctx->draw_state.fill_color = prev_color; return jerry_acquire_value(result); } JERRY_FUNCTION(prv_set_stroke_width) { uint8_t width; ROCKY_ARGS_ASSIGN_OR_RETURN_ERROR( ROCKY_ARG(width), ); graphics_context_set_stroke_width(rocky_api_graphics_get_gcontext(), width); return jerry_create_undefined(); } JERRY_FUNCTION(prv_get_stroke_width) { return jerry_create_number((double)rocky_api_graphics_get_gcontext()->draw_state.stroke_width); } static jerry_value_t prv_graphics_set_color(const jerry_length_t argc, const jerry_value_t argv[], void (*func)(GContext *, GColor)) { GColor color; const RockyArgBinding binding = ROCKY_ARG(color); JS_VAR error_value = rocky_args_assign(argc, argv, &binding, 1); // Canvas APIs do a no-op if the color string is invalid if (!jerry_value_has_error_flag(error_value)) { func(rocky_api_graphics_get_gcontext(), color); }; return jerry_create_undefined(); } #define COLOR_BUFFER_LENGTH (12) T_STATIC void prv_graphics_color_to_char_buffer(GColor8 color, char *buf_out) { if (color.a <= 1) { strncpy(buf_out, "transparent", COLOR_BUFFER_LENGTH); } else { snprintf(buf_out, COLOR_BUFFER_LENGTH, "#%02X%02X%02X", color.r * 85, color.g * 85, color.b * 85); } } static jerry_value_t prv_graphics_get_color_string(GColor8 color) { char buf[COLOR_BUFFER_LENGTH]; prv_graphics_color_to_char_buffer(color, buf); return jerry_create_string((const jerry_char_t *)buf); } JERRY_FUNCTION(prv_set_stroke_style) { return prv_graphics_set_color(argc, argv, graphics_context_set_stroke_color); } JERRY_FUNCTION(prv_get_stroke_style) { return prv_graphics_get_color_string(rocky_api_graphics_get_gcontext()->draw_state.stroke_color); } JERRY_FUNCTION(prv_set_fill_style) { return prv_graphics_set_color(argc, argv, graphics_context_set_fill_color); } JERRY_FUNCTION(prv_get_fill_style) { return prv_graphics_get_color_string(rocky_api_graphics_get_gcontext()->draw_state.fill_color); } JERRY_FUNCTION(prv_fill_radial) { // pblFillRadial(cx, cy, radiu
app_state_get_graphics_context()
<|repo_name|>pebble <|file_sep|>src/fw/applib/rockyjs/api/rocky_api_graphics.c <|fim_prefix|>ssions and * limitations under the License. */ #include "jerry-api.h" #include "rocky_api_graphics.h" #include "rocky_api_graphics_path2d.h" #include "rocky_api_graphics_text.h" #include "rocky_api_util.h" #include "rocky_api_util_args.h" #include "applib/app.h" #include "applib/app_logging.h" #include "applib/ui/ui.h" #include "kernel/pbl_malloc.h" #include "system/logging.h" #include "system/passert.h" #include "util/attributes.h" #include "util/size.h" #include "util/trig.h" #include "process_state/app_state/app_state.h" #include "rocky_api_errors.h" #include "rocky_api_global.h" #include "rocky_api_graphics_color.h" #define ROCKY_EVENT_DRAW "draw" #define ROCKY_EVENT_DRAW_CONTEXT "context" #define ROCKY_REQUESTDRAW "requestDraw" #define ROCKY_CONTEXT2D_CONSTRUCTOR "CanvasRenderingContext2D" #define ROCKY_CONTEXT2D_CANVAS "canvas" #define ROCKY_CONTEXT2D_CLEARRECT "clearRect" #define ROCKY_CONTEXT2D_FILLRECT "fillRect" #define ROCKY_CONTEXT2D_FILLRADIAL "rockyFillRadial" #define ROCKY_CONTEXT2D_STROKERECT "strokeRect" #define ROCKY_CONTEXT2D_LINEWIDTH "lineWidth" #define ROCKY_CONTEXT2D_STROKESTYLE "strokeStyle" #define ROCKY_CONTEXT2D_FILLSTYLE "fillStyle" #define ROCKY_CONTEXT2D_SAVE "save" #define ROCKY_CONTEXT2D_RESTORE "restore" #define ROCKY_CANVAS_CONSTRUCTOR "CanvasElement" #define ROCKY_CANVAS_CLIENTWIDTH "clientWidth" #define ROCKY_CANVAS_CLIENTHEIGHT "clientHeight" #define ROCKY_CANVAS_UNOBSTRUCTEDLEFT "unobstructedLeft" #define ROCKY_CANVAS_UNOBSTRUCTEDTOP "unobstructedTop" #define ROCKY_CANVAS_UNOBSTRUCTEDWIDTH "unobstructedWidth" #define ROCKY_CANVAS_UNOBSTRUCTEDHEIGHT "unobstructedHeight" typedef struct { ListNode node; GDrawState draw_state; } Context2DStoredState; // TODO: PBL-35780 make this part of app_state_get_rocky_runtime_context() SECTION(".rocky_bss") static Context2DStoredState *s_canvas_context_2d_stored_states; T_STATIC jerry_value_t prv_create_canvas_context_2d_for_layer(Layer *layer) { JS_VAR context_2d = rocky_create_with_constructor(ROCKY_CONTEXT2D_CONSTRUCTOR, /* no args: */ NULL, 0); JS_VAR canvas = jerry_get_object_field(context_2d, ROCKY_CONTEXT2D_CANVAS); { JS_VAR client_width = jerry_create_number(layer->bounds.size.w); JS_VAR client_height = jerry_create_number(layer->bounds.size.h); jerry_set_object_field(canvas, ROCKY_CANVAS_CLIENTWIDTH, client_width); jerry_set_object_field(canvas, ROCKY_CANVAS_CLIENTHEIGHT, client_height); } { GRect uo_rect; layer_get_unobstructed_bounds(layer, &uo_rect); JS_VAR unobstructed_left = jerry_create_number(uo_rect.origin.x); JS_VAR unobstructed_right = jerry_create_number(uo_rect.origin.y); JS_VAR unobstructed_width = jerry_create_number(uo_rect.size.w); JS_VAR unobstructed_height = jerry_create_number(uo_rect.size.h); jerry_set_object_field(canvas, ROCKY_CANVAS_UNOBSTRUCTEDLEFT, unobstructed_left); jerry_set_object_field(canvas, ROCKY_CANVAS_UNOBSTRUCTEDTOP, unobstructed_right); jerry_set_object_field(canvas, ROCKY_CANVAS_UNOBSTRUCTEDWIDTH, unobstructed_width); jerry_set_object_field(canvas, ROCKY_CANVAS_UNOBSTRUCTEDHEIGHT, unobstructed_height); } return jerry_acquire_value(context_2d); } static void prv_rocky_update_proc(Layer *layer, GContext *ctx) { if (!rocky_global_has_event_handlers(ROCKY_EVENT_DRAW)) { return; } rocky_api_graphics_text_reset_state(); rocky_api_graphics_path2d_reset_state(); JS_VAR event = rocky_global_create_event(ROCKY_EVENT_DRAW); JS_VAR context_2d = prv_create_canvas_context_2d_for_layer(layer); jerry_set_object_field(event, ROCKY_EVENT_DRAW_CONTEXT, context_2d); rocky_global_call_event_handlers(event); rocky_api_graphics_path2d_reset_state(); } JERRY_FUNCTION(prv_request_draw) { Window *const top_window = app_window_stack_get_top_window(); if (!top_window) { return jerry_create_undefined(); } layer_mark_dirty(&top_window->layer); return jerry_create_undefined(); } GContext *rocky_api_graphics_get_gcontext(void) { return <|fim_suffix|>; } static jerry_value_t prv_rect_precise_call(const jerry_length_t argc, const jerry_value_t argv[], void (*func)(GContext *, const GRectPrecise *)) { GRectPrecise rect; ROCKY_ARGS_ASSIGN_OR_RETURN_ERROR(ROCKY_ARG(rect)); GContext *const ctx = rocky_api_graphics_get_gcontext(); func(ctx, &rect); return jerry_create_undefined(); } static GRect prv_grect_from_precise(const GRectPrecise *rect) { const int16_t x = Fixed_S16_3_rounded_int(rect->origin.x); const int16_t y = Fixed_S16_3_rounded_int(rect->origin.y); const int16_t w = Fixed_S16_3_rounded_int(grect_precise_get_max_x(rect)) - x; const int16_t h = Fixed_S16_3_rounded_int(grect_precise_get_max_y(rect)) - y; return GRect(x, y, w, h); } static jerry_value_t prv_rect_call(const jerry_length_t argc, const jerry_value_t argv[], void (*func)(GContext *, const GRect *)) { GRectPrecise prect; ROCKY_ARGS_ASSIGN_OR_RETURN_ERROR( ROCKY_ARG(prect), ); GContext *const ctx = rocky_api_graphics_get_gcontext(); const GRect rect = prv_grect_from_precise(&prect); func(ctx, &rect); return jerry_create_undefined(); } JERRY_FUNCTION(prv_fill_rect) { return prv_rect_call(argc, argv, graphics_fill_rect); } static void prv_draw_rect_impl(GContext *ctx, const GRectPrecise *rect) { GRectPrecise adjusted_rect = *rect; adjusted_rect.origin.x.raw_value -= FIXED_S16_3_HALF.raw_value; adjusted_rect.origin.y.raw_value -= FIXED_S16_3_HALF.raw_value; graphics_draw_rect_precise(ctx, &adjusted_rect); } JERRY_FUNCTION(prv_stroke_rect) { return prv_rect_precise_call(argc, argv, prv_draw_rect_impl); } JERRY_FUNCTION(prv_clear_rect) { GContext *const ctx = rocky_api_graphics_get_gcontext(); const GColor prev_color = ctx->draw_state.fill_color; ctx->draw_state.fill_color = GColorBlack; JS_VAR result = prv_rect_call(argc, argv, graphics_fill_rect); ctx->draw_state.fill_color = prev_color; return jerry_acquire_value(result); } JERRY_FUNCTION(prv_set_stroke_width) { uint8_t width; ROCKY_ARGS_ASSIGN_OR_RETURN_ERROR( ROCKY_ARG(width), ); graphics_context_set_stroke_width(rocky_api_graphics_get_gcontext(), width); return jerry_create_undefined(); } JERRY_FUNCTION(prv_get_stroke_width) { return jerry_create_number((double)rocky_api_graphics_get_gcontext()->draw_state.stroke_width); } static jerry_value_t prv_graphics_set_color(const jerry_length_t argc, const jerry_value_t argv[], void (*func)(GContext *, GColor)) { GColor color; const RockyArgBinding binding = ROCKY_ARG(color); JS_VAR error_value = rocky_args_assign(argc, argv, &binding, 1); // Canvas APIs do a no-op if the color string is invalid if (!jerry_value_has_error_flag(error_value)) { func(rocky_api_graphics_get_gcontext(), color); }; return jerry_create_undefined(); } #define COLOR_BUFFER_LENGTH (12) T_STATIC void prv_graphics_color_to_char_buffer(GColor8 color, char *buf_out) { if (color.a <= 1) { strncpy(buf_out, "transparent", COLOR_BUFFER_LENGTH); } else { snprintf(buf_out, COLOR_BUFFER_LENGTH, "#%02X%02X%02X", color.r * 85, color.g * 85, color.b * 85); } } static jerry_value_t prv_graphics_get_color_string(GColor8 color) { char buf[COLOR_BUFFER_LENGTH]; prv_graphics_color_to_char_buffer(color, buf); return jerry_create_string((const jerry_char_t *)buf); } JERRY_FUNCTION(prv_set_stroke_style) { return prv_graphics_set_color(argc, argv, graphics_context_set_stroke_color); } JERRY_FUNCTION(prv_get_stroke_style) { return prv_graphics_get_color_string(rocky_api_graphics_get_gcontext()->draw_state.stroke_color); } JERRY_FUNCTION(prv_set_fill_style) { return prv_graphics_set_color(argc, argv, graphics_context_set_fill_color); } JERRY_FUNCTION(prv_get_fill_style) { return prv_graphics_get_color_string(rocky_api_graphics_get_gcontext()->draw_state.fill_color); } JERRY_FUNCTION(prv_fill_radial) { // pblFillRadial(cx, cy, radiu<|fim_middle|>app_state_get_graphics_context()<|endoftext|>
masked_node
argument_list
tests/fw/services/activity/test_activity_insights.c
prv_add_sleep_session(0.5, 1.5); activity_insights_process_sleep_data(rtc_get_time()); cl_assert_equal_i(s_data.pins_added, 2); } // --------------------------------------------------------------------------------------- // Make sure we don't push a pin when we have no history to compare against void test_activity_insights__sleep_summary_no_history(void) { // Tests init with zero history activity_insights_init(rtc_get_time()); // Make sure we don't trigger as soon as we're awake s_data.metric_history[ActivityMetricSleepState][0] = ActivitySleepStateAwake; s_data.metric_history[ActivityMetricSleepExitAtSeconds][0] = 7 * SECONDS_PER_HOUR; s_data.metric_history[ActivityMetricSleepStateSeconds][0] = 30 * SECONDS_PER_MINUTE; activity_insights_process_sleep_data(rtc_get_time()); cl_assert_equal_i(s_data.pins_added, 0); } // --------------------------------------------------------------------------------------- void test_activity_insights__activation_delay_insights_time_trigger(void) { time_t now = mktime(&s_init_time_tm); prv_set_activation_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 0); now += SECONDS_PER_DAY; // Jan 2 @ 10:00am rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 0); now += 8 * SECONDS_PER_HOUR; // Jan 2 @ 6:00pm rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 1); now += (3 * SECONDS_PER_DAY) + (2 * SECONDS_PER_HOUR); // Jan 5 @ 8:00pm rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 1); s_health_app_opened_version = 1; now += 30 * SECONDS_PER_MINUTE; // Jan 5 @ 8:30pm rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 2); now += 6 * SECONDS_PER_DAY; // Jan 11 @ 8:30pm rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 3); } // --------------------------------------------------------------------------------------- void test_activity_insights__activation_delay_insights_fifteen_interval_trigger(void) { time_t now = mktime(&s_init_time_tm); prv_set_activation_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 0); now += SECONDS_PER_DAY + (8 * SECONDS_PER_HOUR) + (5 * SECONDS_PER_MINUTE); // Jan 2 @ 6:05pm rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 0); now += (10 * SECONDS_PER_MINUTE); // Jan 2 @ 6:15pm rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 1); } // Make sure that when the watch resets, we retain state properly void test_activity_insights__nap_session_power_cycle(void) { // PBL-36355 Disable nap notifications // Enable this unit test when re-enabling nap session notifications #if 0 prv_set_sleep_history_avg(); activity_insights_init(rtc_get_time()); // Common metrics s_data.metric_history[ActivityMetricSleepState][0] = ActivitySleepStateAwake; s_data.metric_history[ActivityMetricSleepStateSeconds][0] = 30 * SECONDS_PER_MINUTE; s_data.metric_history[ActivityMetricSleepEnterAtSeconds][0] = 0; // Push a pin rtc_set_time(rtc_get_time() + 5 * SECONDS_PER_HOUR); prv_add_nap_session(0, 1); activity_insights_process_minute_data(rtc_get_time()); cl_assert_equal_i(s_data.pins_added, 1); // Re-init (simulates power cycle) and make sure we don't add a pin again activity_insights_init(rtc_get_time()); activity_insights_process_minute_data
; cl_assert_equal_i(s_data.pins_added, 1); // Make sure we still trigger properly after a power cycle activity_insights_init(rtc_get_time()); rtc_set_time(rtc_get_time() + 2 * SECONDS_PER_HOUR); prv_add_nap_session(0.5, 1.5); activity_insights_process_minute_data(rtc_get_time()); cl_assert_equal_i(s_data.pins_added, 2); #endif } // Make sure that when the watch resets, we retain state properly void test_activity_insights__walk_session_power_cycle(void) { activity_insights_init(rtc_get_time()); // Common metrics s_data.metric_history[ActivityMetricSleepState][0] = ActivitySleepStateAwake; s_data.metric_history[ActivityMetricSleepStateSeconds][0] = 30 * SECONDS_PER_MINUTE; s_data.metric_history[ActivityMetricSleepEnterAtSeconds][0] = 0; // Push a pin rtc_set_time(rtc_get_time() + 5 * SECONDS_PER_HOUR); prv_add_walk_session(0, 1); rtc_set_time(rtc_get_time() + 2 * SECONDS_PER_HOUR); activity_insights_process_minute_data(rtc_get_time()); cl_assert_equal_i(s_data.notifs_shown, 1); // Re-init (simulates power cycle) and make sure we don't add a pin again activity_insights_init(rtc_get_time()); activity_insights_process_minute_data(rtc_get_time()); cl_assert_equal_i(s_data.notifs_shown, 1); // Make sure we still trigger properly after a power cycle activity_insights_init(rtc_get_time()); prv_add_walk_session(0, 1); rtc_set_time(rtc_get_time() + 2 * SECONDS_PER_HOUR); activity_insights_process_minute_data(rtc_get_time()); cl_assert_equal_i(s_data.notifs_shown, 2); }
(rtc_get_time())
<|repo_name|>pebble <|file_sep|>tests/fw/services/activity/test_activity_insights.c <|fim_prefix|> prv_add_sleep_session(0.5, 1.5); activity_insights_process_sleep_data(rtc_get_time()); cl_assert_equal_i(s_data.pins_added, 2); } // --------------------------------------------------------------------------------------- // Make sure we don't push a pin when we have no history to compare against void test_activity_insights__sleep_summary_no_history(void) { // Tests init with zero history activity_insights_init(rtc_get_time()); // Make sure we don't trigger as soon as we're awake s_data.metric_history[ActivityMetricSleepState][0] = ActivitySleepStateAwake; s_data.metric_history[ActivityMetricSleepExitAtSeconds][0] = 7 * SECONDS_PER_HOUR; s_data.metric_history[ActivityMetricSleepStateSeconds][0] = 30 * SECONDS_PER_MINUTE; activity_insights_process_sleep_data(rtc_get_time()); cl_assert_equal_i(s_data.pins_added, 0); } // --------------------------------------------------------------------------------------- void test_activity_insights__activation_delay_insights_time_trigger(void) { time_t now = mktime(&s_init_time_tm); prv_set_activation_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 0); now += SECONDS_PER_DAY; // Jan 2 @ 10:00am rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 0); now += 8 * SECONDS_PER_HOUR; // Jan 2 @ 6:00pm rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 1); now += (3 * SECONDS_PER_DAY) + (2 * SECONDS_PER_HOUR); // Jan 5 @ 8:00pm rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 1); s_health_app_opened_version = 1; now += 30 * SECONDS_PER_MINUTE; // Jan 5 @ 8:30pm rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 2); now += 6 * SECONDS_PER_DAY; // Jan 11 @ 8:30pm rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 3); } // --------------------------------------------------------------------------------------- void test_activity_insights__activation_delay_insights_fifteen_interval_trigger(void) { time_t now = mktime(&s_init_time_tm); prv_set_activation_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 0); now += SECONDS_PER_DAY + (8 * SECONDS_PER_HOUR) + (5 * SECONDS_PER_MINUTE); // Jan 2 @ 6:05pm rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 0); now += (10 * SECONDS_PER_MINUTE); // Jan 2 @ 6:15pm rtc_set_time(now); activity_insights_process_minute_data(now); cl_assert_equal_i(fake_kernel_services_notifications_ancs_notifications_count(), 1); } // Make sure that when the watch resets, we retain state properly void test_activity_insights__nap_session_power_cycle(void) { // PBL-36355 Disable nap notifications // Enable this unit test when re-enabling nap session notifications #if 0 prv_set_sleep_history_avg(); activity_insights_init(rtc_get_time()); // Common metrics s_data.metric_history[ActivityMetricSleepState][0] = ActivitySleepStateAwake; s_data.metric_history[ActivityMetricSleepStateSeconds][0] = 30 * SECONDS_PER_MINUTE; s_data.metric_history[ActivityMetricSleepEnterAtSeconds][0] = 0; // Push a pin rtc_set_time(rtc_get_time() + 5 * SECONDS_PER_HOUR); prv_add_nap_session(0, 1); activity_insights_process_minute_data(rtc_get_time()); cl_assert_equal_i(s_data.pins_added, 1); // Re-init (simulates power cycle) and make sure we don't add a pin again activity_insights_init(rtc_get_time()); activity_insights_process_minute_data<|fim_suffix|>; cl_assert_equal_i(s_data.pins_added, 1); // Make sure we still trigger properly after a power cycle activity_insights_init(rtc_get_time()); rtc_set_time(rtc_get_time() + 2 * SECONDS_PER_HOUR); prv_add_nap_session(0.5, 1.5); activity_insights_process_minute_data(rtc_get_time()); cl_assert_equal_i(s_data.pins_added, 2); #endif } // Make sure that when the watch resets, we retain state properly void test_activity_insights__walk_session_power_cycle(void) { activity_insights_init(rtc_get_time()); // Common metrics s_data.metric_history[ActivityMetricSleepState][0] = ActivitySleepStateAwake; s_data.metric_history[ActivityMetricSleepStateSeconds][0] = 30 * SECONDS_PER_MINUTE; s_data.metric_history[ActivityMetricSleepEnterAtSeconds][0] = 0; // Push a pin rtc_set_time(rtc_get_time() + 5 * SECONDS_PER_HOUR); prv_add_walk_session(0, 1); rtc_set_time(rtc_get_time() + 2 * SECONDS_PER_HOUR); activity_insights_process_minute_data(rtc_get_time()); cl_assert_equal_i(s_data.notifs_shown, 1); // Re-init (simulates power cycle) and make sure we don't add a pin again activity_insights_init(rtc_get_time()); activity_insights_process_minute_data(rtc_get_time()); cl_assert_equal_i(s_data.notifs_shown, 1); // Make sure we still trigger properly after a power cycle activity_insights_init(rtc_get_time()); prv_add_walk_session(0, 1); rtc_set_time(rtc_get_time() + 2 * SECONDS_PER_HOUR); activity_insights_process_minute_data(rtc_get_time()); cl_assert_equal_i(s_data.notifs_shown, 2); } <|fim_middle|>(rtc_get_time())<|endoftext|>
masked_node
argument_list
tests/fw/graphics/test_graphics_draw_round_rect.template.c
heck(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_r0_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 11); graphics_draw_round_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP, 1); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_r1_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 11); graphics_draw_round_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP, 2); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_r2_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 11); graphics_draw_round_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP, 3); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_r3_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 11); graphics_draw_round_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP, ((MIN(RECT_WIDTH, RECT_HEIGHT)) / 2) - 1); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_rmax_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); // Should not draw anything setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 11); graphics_draw_round_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP, ((MIN(RECT_WIDTH, RECT_HEIGHT)) / 2)); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_rmax1_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); // Should not draw anything setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 11); graphics_draw_round_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP, ((MIN(RECT_WIDTH, RECT_HEIGHT)) / 2) + 1); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_rmax2_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); } #define OFFSET_RECT_NO_CLIP GRect(20, 10, 144, 168) #define OFFSET_RECT_CLIP_XY GRect(20, 10, 20, 20) #define OFFSET_RECT_CLIP_NXNY GRect(20, 10, 144, 168) #define OFFSET_DRAW_RECT_NO_CLIP GRect(6, 6, RECT_WIDTH, RECT_HEIGHT) #define OFFSET_DRAW_RECT_CLIP_XY GRect(6, 6, RECT_WIDTH, RECT_HEIGHT) #define OFFSET_DRAW_RECT_CLIP_NXNY GRect(-16, -16, RECT_WIDTH, RECT_HEIGHT) void test_graphics_draw_round_rect_${BIT_DEPTH_NAME}__offset_aa_sw(void) { GContext ctx; test_graphics_context_init(&ctx, fb); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 // AA = true, SW = 1 setup_test_aa_sw(&ctx, fb, OFFSET_RECT_NO_CLIP, OFFSET_RECT_NO_CLIP, true, 1); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_NO_CLIP, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw1_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_XY, OFFSET_RECT_CLIP_XY, true, 1); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_XY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw1_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_NXNY, OFFSET_RECT_CLIP_NXNY, true, 1); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_NXNY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw1_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // AA = true, SW = 2 setup_test_aa_sw(&ctx, fb, OFFSET_RECT_NO_CLIP, OFFSET_RECT_NO_CLIP, true, 2); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_NO_CLIP, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw2_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_XY, OFFSET_RECT_CLIP_XY, true, 2); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_XY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw2_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_NXNY, OFFSET_RECT_CLIP_NXNY, true, 2); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_NXNY, RADIUS_DEFAULT); cl_check
; #endif // AA = true, SW = 3 setup_test_aa_sw(&ctx, fb, OFFSET_RECT_NO_CLIP, OFFSET_RECT_NO_CLIP, true, 3); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_NO_CLIP, RADIUS_DEFAULT); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw3_no_clip.${BIT_DEPTH_NAME}.pbi")); #endif setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_XY, OFFSET_RECT_CLIP_XY, true, 3); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_XY, RADIUS_DEFAULT); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw3_clip_xy.${BIT_DEPTH_NAME}.pbi")); #endif setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_NXNY, OFFSET_RECT_CLIP_NXNY, true, 3); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_NXNY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw3_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 // AA = true, SW = 4 setup_test_aa_sw(&ctx, fb, OFFSET_RECT_NO_CLIP, OFFSET_RECT_NO_CLIP, true, 4); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_NO_CLIP, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw4_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_XY, OFFSET_RECT_CLIP_XY, true, 4); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_XY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw4_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_NXNY, OFFSET_RECT_CLIP_NXNY, true, 4); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_NXNY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw4_clip_nxny.${BIT_DEPTH_NAME}.pbi")); #endif // AA = true, SW = 5 setup_test_aa_sw(&ctx, fb, OFFSET_RECT_NO_CLIP, OFFSET_RECT_NO_CLIP, true, 5); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_NO_CLIP, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw5_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_XY, OFFSET_RECT_CLIP_XY, true, 5); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_XY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw5_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_NXNY, OFFSET_RECT_CLIP_NXNY, true, 5); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_NXNY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw5_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // AA = true, SW = 11 setup_test_aa_sw(&ctx, fb, OFFSET_RECT_NO_CLIP, OFFSET_RECT_NO_CLIP, true, 11); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_NO_CLIP, RADIUS_DEFAULT); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); #endif setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_XY, OFFSET_RECT_CLIP_XY, true, 11); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_XY, RADIUS_DEFAULT); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw11_clip_xy.${BIT_DEPTH_NAME}.pbi")); #endif setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_NXNY, OFFSET_RECT_CLIP_NXNY, true, 11); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_NXNY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw11_clip_nxny.${BIT_DEPTH_NAME}.pbi")); } void test_graphics_draw_round_rect_${BIT_DEPTH_NAME}__offset_sw(void) { GContext ctx; test_graphics_context_init(&ctx, fb
(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw2_clip_nxny.${BIT_DEPTH_NAME}.pbi"))
<|repo_name|>pebble <|file_sep|>tests/fw/graphics/test_graphics_draw_round_rect.template.c <|fim_prefix|>heck(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_r0_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 11); graphics_draw_round_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP, 1); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_r1_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 11); graphics_draw_round_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP, 2); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_r2_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 11); graphics_draw_round_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP, 3); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_r3_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 11); graphics_draw_round_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP, ((MIN(RECT_WIDTH, RECT_HEIGHT)) / 2) - 1); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_rmax_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); // Should not draw anything setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 11); graphics_draw_round_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP, ((MIN(RECT_WIDTH, RECT_HEIGHT)) / 2)); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_rmax1_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); // Should not draw anything setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 11); graphics_draw_round_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP, ((MIN(RECT_WIDTH, RECT_HEIGHT)) / 2) + 1); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_origin_rmax2_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); } #define OFFSET_RECT_NO_CLIP GRect(20, 10, 144, 168) #define OFFSET_RECT_CLIP_XY GRect(20, 10, 20, 20) #define OFFSET_RECT_CLIP_NXNY GRect(20, 10, 144, 168) #define OFFSET_DRAW_RECT_NO_CLIP GRect(6, 6, RECT_WIDTH, RECT_HEIGHT) #define OFFSET_DRAW_RECT_CLIP_XY GRect(6, 6, RECT_WIDTH, RECT_HEIGHT) #define OFFSET_DRAW_RECT_CLIP_NXNY GRect(-16, -16, RECT_WIDTH, RECT_HEIGHT) void test_graphics_draw_round_rect_${BIT_DEPTH_NAME}__offset_aa_sw(void) { GContext ctx; test_graphics_context_init(&ctx, fb); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 // AA = true, SW = 1 setup_test_aa_sw(&ctx, fb, OFFSET_RECT_NO_CLIP, OFFSET_RECT_NO_CLIP, true, 1); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_NO_CLIP, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw1_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_XY, OFFSET_RECT_CLIP_XY, true, 1); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_XY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw1_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_NXNY, OFFSET_RECT_CLIP_NXNY, true, 1); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_NXNY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw1_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // AA = true, SW = 2 setup_test_aa_sw(&ctx, fb, OFFSET_RECT_NO_CLIP, OFFSET_RECT_NO_CLIP, true, 2); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_NO_CLIP, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw2_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_XY, OFFSET_RECT_CLIP_XY, true, 2); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_XY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw2_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_NXNY, OFFSET_RECT_CLIP_NXNY, true, 2); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_NXNY, RADIUS_DEFAULT); cl_check<|fim_suffix|>; #endif // AA = true, SW = 3 setup_test_aa_sw(&ctx, fb, OFFSET_RECT_NO_CLIP, OFFSET_RECT_NO_CLIP, true, 3); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_NO_CLIP, RADIUS_DEFAULT); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw3_no_clip.${BIT_DEPTH_NAME}.pbi")); #endif setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_XY, OFFSET_RECT_CLIP_XY, true, 3); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_XY, RADIUS_DEFAULT); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw3_clip_xy.${BIT_DEPTH_NAME}.pbi")); #endif setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_NXNY, OFFSET_RECT_CLIP_NXNY, true, 3); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_NXNY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw3_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 // AA = true, SW = 4 setup_test_aa_sw(&ctx, fb, OFFSET_RECT_NO_CLIP, OFFSET_RECT_NO_CLIP, true, 4); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_NO_CLIP, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw4_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_XY, OFFSET_RECT_CLIP_XY, true, 4); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_XY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw4_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_NXNY, OFFSET_RECT_CLIP_NXNY, true, 4); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_NXNY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw4_clip_nxny.${BIT_DEPTH_NAME}.pbi")); #endif // AA = true, SW = 5 setup_test_aa_sw(&ctx, fb, OFFSET_RECT_NO_CLIP, OFFSET_RECT_NO_CLIP, true, 5); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_NO_CLIP, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw5_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_XY, OFFSET_RECT_CLIP_XY, true, 5); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_XY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw5_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_NXNY, OFFSET_RECT_CLIP_NXNY, true, 5); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_NXNY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw5_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // AA = true, SW = 11 setup_test_aa_sw(&ctx, fb, OFFSET_RECT_NO_CLIP, OFFSET_RECT_NO_CLIP, true, 11); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_NO_CLIP, RADIUS_DEFAULT); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); #endif setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_XY, OFFSET_RECT_CLIP_XY, true, 11); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_XY, RADIUS_DEFAULT); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw11_clip_xy.${BIT_DEPTH_NAME}.pbi")); #endif setup_test_aa_sw(&ctx, fb, OFFSET_RECT_CLIP_NXNY, OFFSET_RECT_CLIP_NXNY, true, 11); graphics_draw_round_rect(&ctx, &OFFSET_DRAW_RECT_CLIP_NXNY, RADIUS_DEFAULT); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw11_clip_nxny.${BIT_DEPTH_NAME}.pbi")); } void test_graphics_draw_round_rect_${BIT_DEPTH_NAME}__offset_sw(void) { GContext ctx; test_graphics_context_init(&ctx, fb<|fim_middle|>(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_round_rect_offset_r4_aa_sw2_clip_nxny.${BIT_DEPTH_NAME}.pbi"))<|endoftext|>
prefix_only
compound_statement
tests/fixtures/activity/step_samples/pbl-25662.c
992, -24, -112}, { 984, 16, -56}, { 1280, 0, -16}, { 1352, -32, 56}, { 1216, -40, 56}, { 1096, -72, 64}, { 992, -104, 64}, { 936, -88, 8}, { 920, -64, -40}, { 864, -72, -88}, { 824, -88, -120}, { 864, -120, -136}, { 896, -128, -112}, { 984, -120, -144}, { 1112, -96, -128}, { 1176, -88, -128}, { 1576, -104, 0}, { 1568, -80, -80}, { 1296, -24, -176}, // 32 seconds { 1072, 16, -288}, { 760, 48, -312}, { 840, -16, -224}, { 1040, -88, -112}, { 1152, -80, -104}, { 1080, -64, -128}, { 968, -32, -160}, { 904, -24, -192}, { 920, -48, -200}, { 960, -72, -208}, { 1024, -104, -232}, { 1000, -104, -232}, { 1016, -104, -224}, { 1032, -112, -208}, { 1048, -128, -184}, { 1072, -120, -152}, { 1072, -96, -136}, { 1240, -96, -64}, { 1744, -32, -200}, { 1200, -24, -80}, { 944, -16, -136}, { 848, -24, -152}, { 1072, 8, -160}, { 1288, -64, -104}, { 1320, -96, -40}, // 33 seconds { 1160, -120, -32}, { 1120, -136, 0}, { 1008, -104, 0}, { 952, -56, -24}, { 944, -48, -48}, { 960, -40, -40}, { 968, -64, -64}, { 968, -56, -88}, { 952, -64, -80}, { 968, -56, -120}, { 968, -32, -152}, { 1008, -24, -152}, { 1056, -24, -152}, { 1128, -32, -144}, { 1400, -96, -72}, { 1624, -72, -40}, { 1392, -24, -32}, { 1168, 0, -128}, { 960, 88, -232}, { 792, 72, -192}, { 832, -40, -128}, { 1048, -96, -88}, { 1216, -120, -80}, { 1080, -104, -144}, { 984, -96, -232}, // 34 seconds { 936, -120, -248}, { 1032, -192, -208}, { 1200, -256, -176}, { 1152, -288, -160}, { 1048, -280, -168}, { 1040, -240, -200}, { 1032, -216, -176}, { 1000, -192, -136}, { 1016, -152, -144}, { 1024, -120, -144}, { 1064, -112, -136}, { 1096, -104, -136}, { 1104, -104, -144}, { 1096, -136, -144}, { 1120, -136, -144}, { 1088, -144, -152}, { 1064, -136, -144}, { 1064, -136, -128}, { 1040, -136, -128}, { 1016, -144, -152}, { 1016, -184, -168}, { 992, -216, -168}, { 984, -232, -208}, { 984, -216, -240}, { 968, -216, -280}, // 35 seconds { 928, -224, -288}, { 936, -256, -296}, { 968, -256, -304}, { 984, -248, -296}, { 968, -232, -296}, { 904, -224, -288}, { 856, -200, -312}, { 840, -200, -280}, { 880, -176, -248}, { 1000, -192, -256}, { 1256, -120, -312}, { 1024, -144, -272}, { 1224, -112, -264}, { 1312, -128, -184}, { 1344, -128, -80}, { 1080, -104, -56}, { 952, -48, -128}, { 928, -32, -128}, { 976, -56, -96}, { 1040, -80, -80}, { 1064, -56, -56}, { 1080, -40, -32}, { 1056, 0, -136}, { 1032, 0, -128}, { 1024, 24, -208}, // 36 seconds { 1024, 0, -208}, { 984, -24, -248}, { 968, -32, -256}, { 984, -24, -240}, { 1008, 0, -248}, { 1024, 0, -208}, { 1056, 8, -200}, { 1112, -8, -208}, { 1416, -56, -152}, { 1496, -56, -136}, { 1160, -56, -160}, { 1000, -16, -264}, { 704, -8, -216}, { 712, -24, -160}, { 1112, -56, -128}, { 1208, -64, -56}, { 1144, -40, -80}, { 1000, -16, -128},
{ 920, 0, -152}, { 960, -48, -184}, { 1024, -56, -184}, { 1016, -80, -168}, { 1016, -40, -176}, { 944, 0, -168}, { 944, 24, -136}, // 37 seconds { 1048, 72, -112}, { 1056, 48, -48}, { 1320, 48, -24}, { 1344, 96, -16}, { 1336, 136, 8}, { 1136, 128, 80}, { 992, 128, 104}, { 1208, 144, 144}, { 1264, 168, 200}, { 1192, 72, 200}, { 1120, 56, 88}, { 1080, 48, -8}, { 1024, 16, -32}, { 968, 8, -64}, { 912, -32, -136}, { 928, -96, -184}, { 1008, -64, -224}, { 1032, -88, -296}, { 1160, -40, -304}, { 1272, -136, -256}, { 1520, -104, -328}, { 1216, -32, -336}, { 896, 16, -296}, { 648, 16, -280}, { 784, 72, -296}, // 38 seconds { 992, 88, -256}, { 1032, 80, -288}, { 944, 72, -304}, { 840, 120, -336}, { 816, 96, -424}, { 800, 16, -448}, { 784, -40, -528}, { 792, -112, -552}, { 800, -144, -544}, { 824, -128, -552}, { 864, -96, -488}, { 944, -88, -448}, { 1000, -96, -424}, { 1016, -88, -376}, { 1200, -112, -344}, { 1640, -80, -472}, { 1240, -64, -384}, { 848, -112, -248}, { 880, -104, -208}, { 1288, 0, -232}, { 1200, -64, -136}, { 976, -128, -88}, { 880, -80, -120}, { 928, -24, -136}, { 928, 8, -144}, // 39 seconds { 888, -8, -208}, { 864, -16, -296}, { 888, -8, -328}, { 920, -24, -320}, { 928, 0, -304}, { 960, 24, -280}, { 1024, 56, -248}, { 1144, 24, -232}, { 1264, -48, -152}, { 1736, -56, -152},
<|repo_name|>pebble <|file_sep|>tests/fixtures/activity/step_samples/pbl-25662.c <|fim_prefix|> 992, -24, -112}, { 984, 16, -56}, { 1280, 0, -16}, { 1352, -32, 56}, { 1216, -40, 56}, { 1096, -72, 64}, { 992, -104, 64}, { 936, -88, 8}, { 920, -64, -40}, { 864, -72, -88}, { 824, -88, -120}, { 864, -120, -136}, { 896, -128, -112}, { 984, -120, -144}, { 1112, -96, -128}, { 1176, -88, -128}, { 1576, -104, 0}, { 1568, -80, -80}, { 1296, -24, -176}, // 32 seconds { 1072, 16, -288}, { 760, 48, -312}, { 840, -16, -224}, { 1040, -88, -112}, { 1152, -80, -104}, { 1080, -64, -128}, { 968, -32, -160}, { 904, -24, -192}, { 920, -48, -200}, { 960, -72, -208}, { 1024, -104, -232}, { 1000, -104, -232}, { 1016, -104, -224}, { 1032, -112, -208}, { 1048, -128, -184}, { 1072, -120, -152}, { 1072, -96, -136}, { 1240, -96, -64}, { 1744, -32, -200}, { 1200, -24, -80}, { 944, -16, -136}, { 848, -24, -152}, { 1072, 8, -160}, { 1288, -64, -104}, { 1320, -96, -40}, // 33 seconds { 1160, -120, -32}, { 1120, -136, 0}, { 1008, -104, 0}, { 952, -56, -24}, { 944, -48, -48}, { 960, -40, -40}, { 968, -64, -64}, { 968, -56, -88}, { 952, -64, -80}, { 968, -56, -120}, { 968, -32, -152}, { 1008, -24, -152}, { 1056, -24, -152}, { 1128, -32, -144}, { 1400, -96, -72}, { 1624, -72, -40}, { 1392, -24, -32}, { 1168, 0, -128}, { 960, 88, -232}, { 792, 72, -192}, { 832, -40, -128}, { 1048, -96, -88}, { 1216, -120, -80}, { 1080, -104, -144}, { 984, -96, -232}, // 34 seconds { 936, -120, -248}, { 1032, -192, -208}, { 1200, -256, -176}, { 1152, -288, -160}, { 1048, -280, -168}, { 1040, -240, -200}, { 1032, -216, -176}, { 1000, -192, -136}, { 1016, -152, -144}, { 1024, -120, -144}, { 1064, -112, -136}, { 1096, -104, -136}, { 1104, -104, -144}, { 1096, -136, -144}, { 1120, -136, -144}, { 1088, -144, -152}, { 1064, -136, -144}, { 1064, -136, -128}, { 1040, -136, -128}, { 1016, -144, -152}, { 1016, -184, -168}, { 992, -216, -168}, { 984, -232, -208}, { 984, -216, -240}, { 968, -216, -280}, // 35 seconds { 928, -224, -288}, { 936, -256, -296}, { 968, -256, -304}, { 984, -248, -296}, { 968, -232, -296}, { 904, -224, -288}, { 856, -200, -312}, { 840, -200, -280}, { 880, -176, -248}, { 1000, -192, -256}, { 1256, -120, -312}, { 1024, -144, -272}, { 1224, -112, -264}, { 1312, -128, -184}, { 1344, -128, -80}, { 1080, -104, -56}, { 952, -48, -128}, { 928, -32, -128}, { 976, -56, -96}, { 1040, -80, -80}, { 1064, -56, -56}, { 1080, -40, -32}, { 1056, 0, -136}, { 1032, 0, -128}, { 1024, 24, -208}, // 36 seconds { 1024, 0, -208}, { 984, -24, -248}, { 968, -32, -256}, { 984, -24, -240}, { 1008, 0, -248}, { 1024, 0, -208}, { 1056, 8, -200}, { 1112, -8, -208}, { 1416, -56, -152}, { 1496, -56, -136}, { 1160, -56, -160}, { 1000, -16, -264}, { 704, -8, -216}, { 712, -24, -160}, { 1112, -56, -128}, { 1208, -64, -56}, { 1144, -40, -80}, { 1000, -16, -128}, <|fim_suffix|><|fim_middle|> { 920, 0, -152}, { 960, -48, -184}, { 1024, -56, -184}, { 1016, -80, -168}, { 1016, -40, -176}, { 944, 0, -168}, { 944, 24, -136}, // 37 seconds { 1048, 72, -112}, { 1056, 48, -48}, { 1320, 48, -24}, { 1344, 96, -16}, { 1336, 136, 8}, { 1136, 128, 80}, { 992, 128, 104}, { 1208, 144, 144}, { 1264, 168, 200}, { 1192, 72, 200}, { 1120, 56, 88}, { 1080, 48, -8}, { 1024, 16, -32}, { 968, 8, -64}, { 912, -32, -136}, { 928, -96, -184}, { 1008, -64, -224}, { 1032, -88, -296}, { 1160, -40, -304}, { 1272, -136, -256}, { 1520, -104, -328}, { 1216, -32, -336}, { 896, 16, -296}, { 648, 16, -280}, { 784, 72, -296}, // 38 seconds { 992, 88, -256}, { 1032, 80, -288}, { 944, 72, -304}, { 840, 120, -336}, { 816, 96, -424}, { 800, 16, -448}, { 784, -40, -528}, { 792, -112, -552}, { 800, -144, -544}, { 824, -128, -552}, { 864, -96, -488}, { 944, -88, -448}, { 1000, -96, -424}, { 1016, -88, -376}, { 1200, -112, -344}, { 1640, -80, -472}, { 1240, -64, -384}, { 848, -112, -248}, { 880, -104, -208}, { 1288, 0, -232}, { 1200, -64, -136}, { 976, -128, -88}, { 880, -80, -120}, { 928, -24, -136}, { 928, 8, -144}, // 39 seconds { 888, -8, -208}, { 864, -16, -296}, { 888, -8, -328}, { 920, -24, -320}, { 928, 0, -304}, { 960, 24, -280}, { 1024, 56, -248}, { 1144, 24, -232}, { 1264, -48, -152}, { 1736, -56, -152},<|endoftext|>
masked_node
while_statement
platform/tintin/boot/libc/string/memcpy.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /////////////////////////////////////// // Implements: // void *memcpy(void *s1, const void *s2, size_t n); // void *memmove(void *s1, const void *s2, size_t n); /////////////////////////////////////// #include <stddef.h> #include <stdint.h> void *memcpy(void * restrict s1, const void * restrict s2, size_t n) { char *dest = (char*)s1; const char *src = (const char*)s2; while (n--) { *dest++ = *src++; } return s1; } void *memmove(void * restrict s1, const void * restrict s2, size_t n) { char *dest = (char*)s1; const char *src = (const char*)s2; if (dest <= src) { while (n--) { *dest++ = *src++; } } else {
} return s1; }
while (n--) { dest[n] = src[n]; }
<|repo_name|>pebble <|file_sep|>platform/tintin/boot/libc/string/memcpy.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /////////////////////////////////////// // Implements: // void *memcpy(void *s1, const void *s2, size_t n); // void *memmove(void *s1, const void *s2, size_t n); /////////////////////////////////////// #include <stddef.h> #include <stdint.h> void *memcpy(void * restrict s1, const void * restrict s2, size_t n) { char *dest = (char*)s1; const char *src = (const char*)s2; while (n--) { *dest++ = *src++; } return s1; } void *memmove(void * restrict s1, const void * restrict s2, size_t n) { char *dest = (char*)s1; const char *src = (const char*)s2; if (dest <= src) { while (n--) { *dest++ = *src++; } } else { <|fim_suffix|> } return s1; } <|fim_middle|>while (n--) { dest[n] = src[n]; }<|endoftext|>
masked_node
call_expression
tests/fw/services/notifications/test_ancs_filtering.c
attr, s_display_name_attr, s_title_attr); cl_assert(s_performed_store); // Make sure the our existing prefs got updated iOSNotifPrefs expected_prefs = { .attr_list = expected_attributes, }; prv_compare_notif_prefs(existing_prefs, &expected_prefs); } void test_ancs_filtering__record_app_existing_display_name(void) { // We got a new app name, make sure it gets updated iOSNotifPrefs prefs = { .attr_list = { .num_attributes = 1, .attributes = (Attribute[]) { { .id = AttributeIdAppName, .cstring = "Phil was here" }, }, }, }; iOSNotifPrefs *existing_prefs = &prefs; AttributeList expected_attributes = { .num_attributes = 3, .attributes = (Attribute[]) { { .id = AttributeIdAppName, .cstring = "Awesome" }, { .id = AttributeIdMuteDayOfWeek, .uint8 = MuteBitfield_None }, { .id = AttributeIdLastUpdated, .uint32 = s_now }, } }; s_expected_attributes = &expected_attributes; ancs_filtering_record_app(&existing_prefs, s_app_id_attr, s_display_name_attr, s_title_attr); cl_assert(s_performed_store); // Make sure the our existing prefs got updated iOSNotifPrefs expected_prefs = { .attr_list = expected_attributes, }; prv_compare_notif_prefs(existing_prefs, &expected_prefs); } void test_ancs_filtering__record_app_update_timestamp(void) { // We already have all the default attributes, but it has been a while since we got our last // notification from this source iOSNotifPrefs prefs = { .attr_list = { .num_attributes = 3, .attributes = (Attribute[]) { { .id = AttributeIdAppName, .cstring = "Awesome" }, { .id = AttributeIdMuteDayOfWeek, .uint8 = MuteBitfield_None }, { .id = AttributeIdLastUpdated, .uint32 = s_now }, }, }, }; iOSNotifPrefs *existing_prefs = &prefs; s_now += SECONDS_PER_DAY - 1; ancs_filtering_record_app(&existing_prefs, s_app_id_attr, s_display_name_attr, s_title_attr); cl_assert(!s_performed_store); s_now += 2; AttributeList expected_attributes = { .num_attributes = 3, .attributes = (Attribute[]) { { .id = AttributeIdAppName, .cstring = "Awesome" }, { .id = AttributeIdMuteDayOfWeek, .uint8 = MuteBitfield_None }, { .id = AttributeIdLastUpdated, .uint32 = s_now }, } }; s_expected_attributes = &expected_attributes; ancs_filtering_record_app(&existing_prefs, s_app_id_attr, s_display_name_attr, s_title_attr); cl_assert(s_performed_store); // Make sure the our existing prefs got updated iOSNotifPrefs expected_prefs = { .attr_list = expected_attributes, }; prv_compare_notif_prefs(existing_prefs, &expected_prefs); } void test_ancs_filtering__should_ignore_because_muted(void) { iOSNotifPrefs mute_always = { .attr_list = { .num_attributes = 1, .attributes = (Attribute[]) { { .id = AttributeIdMuteDayOfWeek, .uint8 = 0x7F }, } } }; iOSNotifPrefs mute_weekends = { .attr_list = { .num_attributes = 1, .attributes = (Attribute[]) { { .id = AttributeIdMuteDayOfWeek, .uint8 = 0x41 }, } } }; iOSNotifPrefs mute_weekdays = { .attr_list = { .num_attributes = 1, .attributes = (Attribute[]) { { .id = AttributeIdMuteDayOfWeek, .uint8 = 0x3E }, } } }; s_now = 1451606400; // Friday Jan 1, 2016 cl_assert(ancs_filtering_is_muted(&mute_always)); cl_assert(!ancs_filtering_is_muted(&mute_weekends)); cl_assert(ancs_filtering_is_muted(&mute_weekdays)); s_now += SECONDS_PER_DAY; // Saturday Jan 2, 2016 cl_assert(ancs_filtering_is_muted(&mute_always)); cl_assert(ancs_filtering_is_muted(&mute_weekends)); cl_assert(!ancs_filtering_is_muted(&mute_weekdays)); s_now += SECONDS_PER_DAY; // Sunday Jan 3, 2016 cl_assert(ancs_filtering_is_muted(&mute_always)); cl_assert(ancs_filtering_is_muted(&mute_weekends)); cl_assert(!ancs_filtering_is_muted(&mute_weekdays)); s_now += SECONDS_PER_DAY; // Monday Jan 4, 2016 cl_assert(ancs_filtering_is_muted(&mute_always)); cl_assert(!
); cl_assert(ancs_filtering_is_muted(&mute_weekdays)); } void test_ancs_filtering__record_app_no_display_name(void) { iOSNotifPrefs *existing_prefs = NULL; // No display name so we expect the app name to be the title AttributeList expected_attributes = { .num_attributes = 3, .attributes = (Attribute[]) { { .id = AttributeIdAppName, .cstring = "Apple Pay = :(" }, { .id = AttributeIdMuteDayOfWeek, .uint8 = MuteBitfield_None }, { .id = AttributeIdLastUpdated, .uint32 = s_now }, } }; s_expected_attributes = &expected_attributes; ancs_filtering_record_app(&existing_prefs, s_app_id_attr, NULL, s_title_attr); cl_assert(s_performed_store); // Make sure the our existing prefs got updated iOSNotifPrefs expected_prefs = { .attr_list = expected_attributes, }; prv_compare_notif_prefs(existing_prefs, &expected_prefs); }
ancs_filtering_is_muted(&mute_weekends)
<|repo_name|>pebble <|file_sep|>tests/fw/services/notifications/test_ancs_filtering.c <|fim_prefix|>attr, s_display_name_attr, s_title_attr); cl_assert(s_performed_store); // Make sure the our existing prefs got updated iOSNotifPrefs expected_prefs = { .attr_list = expected_attributes, }; prv_compare_notif_prefs(existing_prefs, &expected_prefs); } void test_ancs_filtering__record_app_existing_display_name(void) { // We got a new app name, make sure it gets updated iOSNotifPrefs prefs = { .attr_list = { .num_attributes = 1, .attributes = (Attribute[]) { { .id = AttributeIdAppName, .cstring = "Phil was here" }, }, }, }; iOSNotifPrefs *existing_prefs = &prefs; AttributeList expected_attributes = { .num_attributes = 3, .attributes = (Attribute[]) { { .id = AttributeIdAppName, .cstring = "Awesome" }, { .id = AttributeIdMuteDayOfWeek, .uint8 = MuteBitfield_None }, { .id = AttributeIdLastUpdated, .uint32 = s_now }, } }; s_expected_attributes = &expected_attributes; ancs_filtering_record_app(&existing_prefs, s_app_id_attr, s_display_name_attr, s_title_attr); cl_assert(s_performed_store); // Make sure the our existing prefs got updated iOSNotifPrefs expected_prefs = { .attr_list = expected_attributes, }; prv_compare_notif_prefs(existing_prefs, &expected_prefs); } void test_ancs_filtering__record_app_update_timestamp(void) { // We already have all the default attributes, but it has been a while since we got our last // notification from this source iOSNotifPrefs prefs = { .attr_list = { .num_attributes = 3, .attributes = (Attribute[]) { { .id = AttributeIdAppName, .cstring = "Awesome" }, { .id = AttributeIdMuteDayOfWeek, .uint8 = MuteBitfield_None }, { .id = AttributeIdLastUpdated, .uint32 = s_now }, }, }, }; iOSNotifPrefs *existing_prefs = &prefs; s_now += SECONDS_PER_DAY - 1; ancs_filtering_record_app(&existing_prefs, s_app_id_attr, s_display_name_attr, s_title_attr); cl_assert(!s_performed_store); s_now += 2; AttributeList expected_attributes = { .num_attributes = 3, .attributes = (Attribute[]) { { .id = AttributeIdAppName, .cstring = "Awesome" }, { .id = AttributeIdMuteDayOfWeek, .uint8 = MuteBitfield_None }, { .id = AttributeIdLastUpdated, .uint32 = s_now }, } }; s_expected_attributes = &expected_attributes; ancs_filtering_record_app(&existing_prefs, s_app_id_attr, s_display_name_attr, s_title_attr); cl_assert(s_performed_store); // Make sure the our existing prefs got updated iOSNotifPrefs expected_prefs = { .attr_list = expected_attributes, }; prv_compare_notif_prefs(existing_prefs, &expected_prefs); } void test_ancs_filtering__should_ignore_because_muted(void) { iOSNotifPrefs mute_always = { .attr_list = { .num_attributes = 1, .attributes = (Attribute[]) { { .id = AttributeIdMuteDayOfWeek, .uint8 = 0x7F }, } } }; iOSNotifPrefs mute_weekends = { .attr_list = { .num_attributes = 1, .attributes = (Attribute[]) { { .id = AttributeIdMuteDayOfWeek, .uint8 = 0x41 }, } } }; iOSNotifPrefs mute_weekdays = { .attr_list = { .num_attributes = 1, .attributes = (Attribute[]) { { .id = AttributeIdMuteDayOfWeek, .uint8 = 0x3E }, } } }; s_now = 1451606400; // Friday Jan 1, 2016 cl_assert(ancs_filtering_is_muted(&mute_always)); cl_assert(!ancs_filtering_is_muted(&mute_weekends)); cl_assert(ancs_filtering_is_muted(&mute_weekdays)); s_now += SECONDS_PER_DAY; // Saturday Jan 2, 2016 cl_assert(ancs_filtering_is_muted(&mute_always)); cl_assert(ancs_filtering_is_muted(&mute_weekends)); cl_assert(!ancs_filtering_is_muted(&mute_weekdays)); s_now += SECONDS_PER_DAY; // Sunday Jan 3, 2016 cl_assert(ancs_filtering_is_muted(&mute_always)); cl_assert(ancs_filtering_is_muted(&mute_weekends)); cl_assert(!ancs_filtering_is_muted(&mute_weekdays)); s_now += SECONDS_PER_DAY; // Monday Jan 4, 2016 cl_assert(ancs_filtering_is_muted(&mute_always)); cl_assert(!<|fim_suffix|>); cl_assert(ancs_filtering_is_muted(&mute_weekdays)); } void test_ancs_filtering__record_app_no_display_name(void) { iOSNotifPrefs *existing_prefs = NULL; // No display name so we expect the app name to be the title AttributeList expected_attributes = { .num_attributes = 3, .attributes = (Attribute[]) { { .id = AttributeIdAppName, .cstring = "Apple Pay = :(" }, { .id = AttributeIdMuteDayOfWeek, .uint8 = MuteBitfield_None }, { .id = AttributeIdLastUpdated, .uint32 = s_now }, } }; s_expected_attributes = &expected_attributes; ancs_filtering_record_app(&existing_prefs, s_app_id_attr, NULL, s_title_attr); cl_assert(s_performed_store); // Make sure the our existing prefs got updated iOSNotifPrefs expected_prefs = { .attr_list = expected_attributes, }; prv_compare_notif_prefs(existing_prefs, &expected_prefs); } <|fim_middle|>ancs_filtering_is_muted(&mute_weekends)<|endoftext|>
masked_node
if_statement
tests/fw/ui/test_menu_layer.c
lse, MenuRowAlignNone, false); cl_assert_equal_i(2 * FOCUSED + NORMAL, l.selection.y); cl_assert_equal_i(NORMAL, l.selection.h); cl_assert_equal_b(false, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); // totally wrong menu_layer_set_selected_next(&l, true, MenuRowAlignNone, false); cl_assert_equal_i(2 * FOCUSED, l.selection.y); cl_assert_equal_i(NORMAL, l.selection.h); cl_assert_equal_b(false, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); // WTF?! menu_layer_set_selected_index(&l, MenuIndex(0, 1), MenuRowAlignNone, false); cl_assert_equal_i(2 * FOCUSED - NORMAL, l.selection.y); cl_assert_equal_i(NORMAL, l.selection.h); cl_assert_equal_b(false, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); } void test_menu_layer__center_focused_respects_row_height_for_selection(void) { MenuLayer l; const int height = 180; menu_layer_init(&l, &GRect(10, 10, height, 180)); menu_layer_set_center_focused(&l, true); menu_layer_set_callbacks(&l, NULL, &(MenuLayerCallbacks){ .draw_row = prv_draw_row, .get_num_rows = prv_get_num_rows, .get_cell_height = prv_get_row_height_depending_on_selection_state, }); const int FOCUSED = MENU_CELL_ROUND_FOCUSED_TALL_CELL_HEIGHT; const int NORMAL = menu_cell_basic_cell_height(); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(0, l.selection.y); const int row0_vertically_centered = (height - FOCUSED)/2; cl_assert_equal_i(row0_vertically_centered, scroll_layer_get_content_offset(&l.scroll_layer).y); cl_assert_equal_i(FOCUSED, l.selection.h); cl_assert_equal_b(false, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); menu_layer_set_selected_index(&l, MenuIndex(0, 2), MenuRowAlignNone, false); // new center-focus behavior: adjust for changed row sizes depending on focused row cl_assert(menu_layer_get_center_focused(&l) == true); cl_assert_equal_i(2 * NORMAL, l.selection.y); cl_assert_equal_i(NORMAL - FOCUSED, scroll_layer_get_content_offset(&l.scroll_layer).y); cl_assert_equal_i(FOCUSED, l.selection.h); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); menu_layer_set_selected_next(&l, false, MenuRowAlignNone, false); cl_assert_equal_i(3 * NORMAL, l.selection.y); cl_assert_equal_i(-FOCUSED, scroll_layer_get_content_offset(&l.scroll_layer).y); cl_assert_equal_i(FOCUSED, l.selection.h); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); menu_layer_set_selected_next(&l, true, MenuRowAlignNone, false); cl_assert_equal_i(2 * NORMAL, l.selection.y); cl_assert_equal_i(NORMAL - FOCUSED, scroll_layer_get_content_offset(&l.scroll_layer).y); cl_assert_equal_i(FOCUSED, l.selection.h); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); menu_layer_set_selected_index(&l, MenuIndex(0, 1), MenuRowAlignNone, false); cl_assert_equal_i(1 * NORMAL, l.selection.y); cl_assert_equal_i(2 * NORMAL - FOCUSED, scroll_layer_get_content_offset(&l.scroll_layer).y); cl_assert_equal_i(FOCUSED, l.selection.h); cl_assert_equal_b(false, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); } static void prv_skip_odd_rows(struct MenuLayer *menu_layer, MenuIndex *new_index, MenuIndex old_index, void *callback_context) { if (new_index->row == 1) { new_index->row = 2; }
} void test_menu_layer__center_focused_handles_skipped_rows(void) { MenuLayer l; menu_layer_init(&l, &GRect(10, 10, DISP_COLS, DISP_ROWS)); menu_layer_set_center_focused(&l, true); menu_layer_set_callbacks(&l, NULL, &(MenuLayerCallbacks) { .draw_row = prv_draw_row, .get_num_rows = prv_get_num_rows, .selection_will_change = prv_skip_odd_rows, }); menu_layer_reload_data(&l); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(0, l.selection.y); menu_layer_set_selected_next(&l, false, MenuRowAlignNone, false); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); cl_assert_equal_i(2, menu_layer_get_selected_index(&l).row); const int16_t basic_cell_height = menu_cell_basic_cell_height(); cl_assert_equal_i(2 * basic_cell_height, l.selection.y); menu_layer_set_selected_next(&l, false, MenuRowAlignNone, false); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); cl_assert_equal_i(4, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(4 * basic_cell_height, l.selection.y); menu_layer_set_selected_next(&l, false, MenuRowAlignNone, false); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); cl_assert_equal_i(5, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(5 * basic_cell_height, l.selection.y); menu_layer_set_selected_next(&l, true, MenuRowAlignNone, false); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); cl_assert_equal_i(4, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(4 * basic_cell_height, l.selection.y); } void test_menu_layer__center_focused_handles_skipped_rows_animated(void) { MenuLayer l; menu_layer_init(&l, &GRect(10, 10, DISP_COLS, DISP_ROWS)); menu_layer_set_center_focused(&l, true); menu_layer_set_callbacks(&l, NULL, &(MenuLayerCallbacks) { .draw_row = prv_draw_row, .get_num_rows = prv_get_num_rows, .selection_will_change = prv_skip_odd_rows, }); menu_layer_reload_data(&l); const int16_t basic_cell_height = menu_cell_basic_cell_height(); const int initial_scroll_offset = (DISP_ROWS - basic_cell_height) / 2; cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(0, l.selection.y); cl_assert_equal_i(initial_scroll_offset, l.scroll_layer.content_sublayer.bounds.origin.y); menu_layer_set_selected_next(&l, false, MenuRowAlignNone, true); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); // these values are unchanged until the animation updates them cl_assert_equal_i(0, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(0 * basic_cell_height, l.selection.y); cl_assert_equal_i(initial_scroll_offset, l.scroll_layer.content_sublayer.bounds.origin.y); // in this test setup, we can directly cast an animation to AnimationPrivate AnimationPrivate *ap = (AnimationPrivate *) l.animation.animation; const AnimationImplementation *const impl = ap->implementation; impl->update(l.animation.animation, ANIMATION_NORMALIZED_MAX / 10); // still unchanged cl_assert_equal_i(0, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(0 * basic_cell_height, l.selection.y); cl_assert_equal_i(initial_scroll_offset, l.scroll_layer.content_sublayer.bounds.origin.y); // and updated impl->update(l.animation.animation, ANIMATION_NORMALIZED_MAX * 9 / 10); cl_assert_equal_i(2, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(2 * basic_cell_height, l.selection.y); cl_assert_equal_i(initial_scroll_offset - 2 * basic_cell_height, l.scroll_layer.content_sublayer.bounds.origin.y); animation_unschedule(l.animation.animation); menu_layer_set_selected_next(&l, false, MenuRowAlignNone, true); // these values are unchanged until the animation updates them cl_assert_equal_i(2, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(2 * basic_cell_height, l.selection.y);
if (new_index->row == 3) { new_index->row = 4; }
<|repo_name|>pebble <|file_sep|>tests/fw/ui/test_menu_layer.c <|fim_prefix|>lse, MenuRowAlignNone, false); cl_assert_equal_i(2 * FOCUSED + NORMAL, l.selection.y); cl_assert_equal_i(NORMAL, l.selection.h); cl_assert_equal_b(false, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); // totally wrong menu_layer_set_selected_next(&l, true, MenuRowAlignNone, false); cl_assert_equal_i(2 * FOCUSED, l.selection.y); cl_assert_equal_i(NORMAL, l.selection.h); cl_assert_equal_b(false, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); // WTF?! menu_layer_set_selected_index(&l, MenuIndex(0, 1), MenuRowAlignNone, false); cl_assert_equal_i(2 * FOCUSED - NORMAL, l.selection.y); cl_assert_equal_i(NORMAL, l.selection.h); cl_assert_equal_b(false, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); } void test_menu_layer__center_focused_respects_row_height_for_selection(void) { MenuLayer l; const int height = 180; menu_layer_init(&l, &GRect(10, 10, height, 180)); menu_layer_set_center_focused(&l, true); menu_layer_set_callbacks(&l, NULL, &(MenuLayerCallbacks){ .draw_row = prv_draw_row, .get_num_rows = prv_get_num_rows, .get_cell_height = prv_get_row_height_depending_on_selection_state, }); const int FOCUSED = MENU_CELL_ROUND_FOCUSED_TALL_CELL_HEIGHT; const int NORMAL = menu_cell_basic_cell_height(); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(0, l.selection.y); const int row0_vertically_centered = (height - FOCUSED)/2; cl_assert_equal_i(row0_vertically_centered, scroll_layer_get_content_offset(&l.scroll_layer).y); cl_assert_equal_i(FOCUSED, l.selection.h); cl_assert_equal_b(false, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); menu_layer_set_selected_index(&l, MenuIndex(0, 2), MenuRowAlignNone, false); // new center-focus behavior: adjust for changed row sizes depending on focused row cl_assert(menu_layer_get_center_focused(&l) == true); cl_assert_equal_i(2 * NORMAL, l.selection.y); cl_assert_equal_i(NORMAL - FOCUSED, scroll_layer_get_content_offset(&l.scroll_layer).y); cl_assert_equal_i(FOCUSED, l.selection.h); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); menu_layer_set_selected_next(&l, false, MenuRowAlignNone, false); cl_assert_equal_i(3 * NORMAL, l.selection.y); cl_assert_equal_i(-FOCUSED, scroll_layer_get_content_offset(&l.scroll_layer).y); cl_assert_equal_i(FOCUSED, l.selection.h); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); menu_layer_set_selected_next(&l, true, MenuRowAlignNone, false); cl_assert_equal_i(2 * NORMAL, l.selection.y); cl_assert_equal_i(NORMAL - FOCUSED, scroll_layer_get_content_offset(&l.scroll_layer).y); cl_assert_equal_i(FOCUSED, l.selection.h); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); menu_layer_set_selected_index(&l, MenuIndex(0, 1), MenuRowAlignNone, false); cl_assert_equal_i(1 * NORMAL, l.selection.y); cl_assert_equal_i(2 * NORMAL - FOCUSED, scroll_layer_get_content_offset(&l.scroll_layer).y); cl_assert_equal_i(FOCUSED, l.selection.h); cl_assert_equal_b(false, s_content_available[ContentIndicatorDirectionUp]); cl_assert_equal_b(true, s_content_available[ContentIndicatorDirectionDown]); } static void prv_skip_odd_rows(struct MenuLayer *menu_layer, MenuIndex *new_index, MenuIndex old_index, void *callback_context) { if (new_index->row == 1) { new_index->row = 2; } <|fim_suffix|> } void test_menu_layer__center_focused_handles_skipped_rows(void) { MenuLayer l; menu_layer_init(&l, &GRect(10, 10, DISP_COLS, DISP_ROWS)); menu_layer_set_center_focused(&l, true); menu_layer_set_callbacks(&l, NULL, &(MenuLayerCallbacks) { .draw_row = prv_draw_row, .get_num_rows = prv_get_num_rows, .selection_will_change = prv_skip_odd_rows, }); menu_layer_reload_data(&l); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(0, l.selection.y); menu_layer_set_selected_next(&l, false, MenuRowAlignNone, false); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); cl_assert_equal_i(2, menu_layer_get_selected_index(&l).row); const int16_t basic_cell_height = menu_cell_basic_cell_height(); cl_assert_equal_i(2 * basic_cell_height, l.selection.y); menu_layer_set_selected_next(&l, false, MenuRowAlignNone, false); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); cl_assert_equal_i(4, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(4 * basic_cell_height, l.selection.y); menu_layer_set_selected_next(&l, false, MenuRowAlignNone, false); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); cl_assert_equal_i(5, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(5 * basic_cell_height, l.selection.y); menu_layer_set_selected_next(&l, true, MenuRowAlignNone, false); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); cl_assert_equal_i(4, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(4 * basic_cell_height, l.selection.y); } void test_menu_layer__center_focused_handles_skipped_rows_animated(void) { MenuLayer l; menu_layer_init(&l, &GRect(10, 10, DISP_COLS, DISP_ROWS)); menu_layer_set_center_focused(&l, true); menu_layer_set_callbacks(&l, NULL, &(MenuLayerCallbacks) { .draw_row = prv_draw_row, .get_num_rows = prv_get_num_rows, .selection_will_change = prv_skip_odd_rows, }); menu_layer_reload_data(&l); const int16_t basic_cell_height = menu_cell_basic_cell_height(); const int initial_scroll_offset = (DISP_ROWS - basic_cell_height) / 2; cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(0, l.selection.y); cl_assert_equal_i(initial_scroll_offset, l.scroll_layer.content_sublayer.bounds.origin.y); menu_layer_set_selected_next(&l, false, MenuRowAlignNone, true); cl_assert_equal_i(0, menu_layer_get_selected_index(&l).section); // these values are unchanged until the animation updates them cl_assert_equal_i(0, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(0 * basic_cell_height, l.selection.y); cl_assert_equal_i(initial_scroll_offset, l.scroll_layer.content_sublayer.bounds.origin.y); // in this test setup, we can directly cast an animation to AnimationPrivate AnimationPrivate *ap = (AnimationPrivate *) l.animation.animation; const AnimationImplementation *const impl = ap->implementation; impl->update(l.animation.animation, ANIMATION_NORMALIZED_MAX / 10); // still unchanged cl_assert_equal_i(0, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(0 * basic_cell_height, l.selection.y); cl_assert_equal_i(initial_scroll_offset, l.scroll_layer.content_sublayer.bounds.origin.y); // and updated impl->update(l.animation.animation, ANIMATION_NORMALIZED_MAX * 9 / 10); cl_assert_equal_i(2, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(2 * basic_cell_height, l.selection.y); cl_assert_equal_i(initial_scroll_offset - 2 * basic_cell_height, l.scroll_layer.content_sublayer.bounds.origin.y); animation_unschedule(l.animation.animation); menu_layer_set_selected_next(&l, false, MenuRowAlignNone, true); // these values are unchanged until the animation updates them cl_assert_equal_i(2, menu_layer_get_selected_index(&l).row); cl_assert_equal_i(2 * basic_cell_height, l.selection.y);<|fim_middle|>if (new_index->row == 3) { new_index->row = 4; }<|endoftext|>
prefix_only
argument_list
platform/robert/boot/test/test_system_flash.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include "clar.h" #include "drivers/system_flash.h" #define KiB *1024 // Set bits n..0 in a bit-vector (zero-indexed) #define BITS(n) ((((uint32_t)(1 << ((n) + 1)))) - 1) // Set bits y..x in a bit-vector (x <= y; x, y >= 0) #define BITS_BETWEEN(x, y) (BITS(y) & ~BITS(x-1)) // Yo dawg, I heard you like tests so I put tests in your tests so you can test // your tests while you test! void test_system_flash__bit_range_macros(void) { cl_assert_equal_i(0b1, BITS(0)); cl_assert_equal_i(0b00011111, BITS(4)); cl_assert_equal_i(0b00111111, BITS_BETWEEN(0, 5)); cl_assert_equal_i(0b00111000, BITS_BETWEEN(3, 5)); cl_assert_equal_i(0b00010000, BITS_BETWEEN(4, 4)); } // Flash memory is organized into twelve sectors of unequal sizes. // Sectors 0-3 are 16 KiB. Sector 4 is 64 KiB. // The remaining sectors are 128 KiB. // Bitset of sectors that have been "erased" static uint32_t erased_sector; static bool flash_locked, flash_flags_set; static FLASH_Status return_status; uint8_t *flash_written_data; bool *flash_written_flag; void *source_buffer; uint32_t flash_data_start, flash_data_length; bool callback_called; void test_system_flash__initialize(void) { erased_sector = 0; flash_locked = true; flash_flags_set = false; return_status = FLASH_COMPLETE; flash_written_data = NULL; flash_written_flag = NULL; flash_data_start = 0; flash_data_length = 0; callback_called = false; } void test_system_flash__cleanup(void) { free(flash_written_data); free(flash_written_flag); } void test_system_flash__erase_zero_bytes(void) { cl_assert(system_flash_erase(FLASH_BASE, 0, NULL, NULL)); cl_assert_equal_i(0, erased_sector); cl_assert(flash_locked); } void test_system_flash__erase_one_byte(void) { cl_assert(system_flash_erase(FLASH_BASE, 1, NULL, NULL)); cl_assert_equal_i(BITS_BETWEEN(0, 0), erased_sector); cl_assert(flash_locked); } void test_system_flash__erase_one_byte_in_middle_of_sector(void) { cl_assert(system_flash_erase(FLASH_BASE + 12345, 1, NULL, NULL)); cl_assert_equal_i(BITS_BETWEEN(0, 0), erased_sector); cl_assert(flash_locked); } void test_system_flash__erase_some_sectors_from_beginning(void) { cl_assert
(system_flash_erase(FLASH_BASE, 128 KiB, NULL, NULL))
<|repo_name|>pebble <|file_sep|>platform/robert/boot/test/test_system_flash.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include "clar.h" #include "drivers/system_flash.h" #define KiB *1024 // Set bits n..0 in a bit-vector (zero-indexed) #define BITS(n) ((((uint32_t)(1 << ((n) + 1)))) - 1) // Set bits y..x in a bit-vector (x <= y; x, y >= 0) #define BITS_BETWEEN(x, y) (BITS(y) & ~BITS(x-1)) // Yo dawg, I heard you like tests so I put tests in your tests so you can test // your tests while you test! void test_system_flash__bit_range_macros(void) { cl_assert_equal_i(0b1, BITS(0)); cl_assert_equal_i(0b00011111, BITS(4)); cl_assert_equal_i(0b00111111, BITS_BETWEEN(0, 5)); cl_assert_equal_i(0b00111000, BITS_BETWEEN(3, 5)); cl_assert_equal_i(0b00010000, BITS_BETWEEN(4, 4)); } // Flash memory is organized into twelve sectors of unequal sizes. // Sectors 0-3 are 16 KiB. Sector 4 is 64 KiB. // The remaining sectors are 128 KiB. // Bitset of sectors that have been "erased" static uint32_t erased_sector; static bool flash_locked, flash_flags_set; static FLASH_Status return_status; uint8_t *flash_written_data; bool *flash_written_flag; void *source_buffer; uint32_t flash_data_start, flash_data_length; bool callback_called; void test_system_flash__initialize(void) { erased_sector = 0; flash_locked = true; flash_flags_set = false; return_status = FLASH_COMPLETE; flash_written_data = NULL; flash_written_flag = NULL; flash_data_start = 0; flash_data_length = 0; callback_called = false; } void test_system_flash__cleanup(void) { free(flash_written_data); free(flash_written_flag); } void test_system_flash__erase_zero_bytes(void) { cl_assert(system_flash_erase(FLASH_BASE, 0, NULL, NULL)); cl_assert_equal_i(0, erased_sector); cl_assert(flash_locked); } void test_system_flash__erase_one_byte(void) { cl_assert(system_flash_erase(FLASH_BASE, 1, NULL, NULL)); cl_assert_equal_i(BITS_BETWEEN(0, 0), erased_sector); cl_assert(flash_locked); } void test_system_flash__erase_one_byte_in_middle_of_sector(void) { cl_assert(system_flash_erase(FLASH_BASE + 12345, 1, NULL, NULL)); cl_assert_equal_i(BITS_BETWEEN(0, 0), erased_sector); cl_assert(flash_locked); } void test_system_flash__erase_some_sectors_from_beginning(void) { cl_assert<|fim_suffix|><|fim_middle|>(system_flash_erase(FLASH_BASE, 128 KiB, NULL, NULL))<|endoftext|>
masked_node
call_expression
src/fw/services/normal/notifications/ancs/ancs_filtering.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ancs_filtering.h" #include "drivers/rtc.h" #include "kernel/pbl_malloc.h" #include "services/normal/notifications/alerts_preferences.h" #include "services/normal/timeline/attributes_actions.h" #include "system/logging.h" #include "util/pstring.h" void ancs_filtering_record_app(iOSNotifPrefs **notif_prefs, const ANCSAttribute *app_id, const ANCSAttribute *display_name, const ANCSAttribute *title) { // When we receive a notification, information about the app that sent us the notification // is recorded in the notif_pref_db. We sync this DB with the phone which allows us to // do things like add non ANCS actions, or filter notifications by app // The "default" attributes are merged with any existing attributes. This makes it easy to add // new attributes in the future as well as support EMail / SMS apps which already have data // stored. iOSNotifPrefs *app_notif_prefs = *notif_prefs; const int num_existing_attribtues = app_notif_prefs ? app_notif_prefs->attr_list.num_attributes : 0; AttributeList new_attr_list; attribute_list_init_list(num_existing_attribtues, &new_attr_list); bool list_dirty = false; // Copy over all the existing attributes to our new list if (app_notif_prefs) { for (int i = 0; i < num_existing_attribtues; i++) { new_attr_list.attributes[i] = app_notif_prefs->attr_list.attributes[i]; } } // The app name should be the display name // If there is no display name (Apple Pay) then fallback to the title const ANCSAttribute *app_name_attr = NULL; if (display_name && display_name->length > 0) { app_name_attr = display_name; } else if (title && title->length > 0) { app_name_attr = title; } char *app_name_buff = NULL; if (app_name_attr) { const char *existing_name = ""; if (app_notif_prefs) { existing_name = attribute_get_string(&app_notif_prefs->attr_list, AttributeIdAppName, ""); } if (!pstring_equal_cstring(&app_name_attr->pstr, existing_name)) { // If the existing name doesn't match our new name, update the name app_name_buff =
; pstring_pstring16_to_string(&app_name_attr->pstr, app_name_buff); attribute_list_add_cstring(&new_attr_list, AttributeIdAppName, app_name_buff); list_dirty = true; PBL_LOG(LOG_LEVEL_INFO, "Adding app name to app prefs: <%s>", app_name_buff); } } // Add the mute attribute if we don't have one already // Default the app to not muted const bool already_has_mute = app_notif_prefs && attribute_find(&app_notif_prefs->attr_list, AttributeIdMuteDayOfWeek); if (!already_has_mute) { attribute_list_add_uint8(&new_attr_list, AttributeIdMuteDayOfWeek, MuteBitfield_None); list_dirty = true; } // Add / update the "last seen" timestamp Attribute *last_updated = NULL; if (app_notif_prefs) { last_updated = attribute_find(&app_notif_prefs->attr_list, AttributeIdLastUpdated); } uint32_t now = rtc_get_time(); // Only perform an update if there is no timestamp or the current timestamp is more than a day old if (!last_updated || (last_updated && now > (last_updated->uint32 + SECONDS_PER_DAY))) { attribute_list_add_uint32(&new_attr_list, AttributeIdLastUpdated, now); list_dirty = true; PBL_LOG(LOG_LEVEL_INFO, "Updating / adding timestamp to app prefs"); } if (list_dirty) { // We don't change or add actions at this time TimelineItemActionGroup *new_action_group = NULL; if (app_notif_prefs) { new_action_group = &app_notif_prefs->action_group; } ios_notif_pref_db_store_prefs(app_id->value, app_id->length, &new_attr_list, new_action_group); // Update our copy of the prefs with the new data const size_t buf_size = attributes_actions_get_buffer_size(&new_attr_list, new_action_group); *notif_prefs = kernel_zalloc_check(sizeof(iOSNotifPrefs) + buf_size); uint8_t *buffer = (uint8_t*)*notif_prefs + sizeof(iOSNotifPrefs); attributes_actions_deep_copy(&new_attr_list, &(*notif_prefs)->attr_list, new_action_group, &(*notif_prefs)->action_group, buffer, buffer + buf_size); ios_notif_pref_db_free_prefs(app_notif_prefs); } kernel_free(app_name_buff); attribute_list_destroy_list(&new_attr_list); } uint8_t ancs_filtering_get_mute_type(const iOSNotifPrefs *app_notif_prefs) { if (app_notif_prefs) { return attribute_get_uint8(&app_notif_prefs->attr_list, AttributeIdMuteDayOfWeek, MuteBitfield_None); } return MuteBitfield_None; } bool ancs_filtering_is_muted(const iOSNotifPrefs *app_notif_prefs) { uint8_t mute_type = ancs_filtering_get_mute_type(app_notif_prefs); struct tm now_tm; time_t now = rtc_get_time(); localtime_r(&now, &now_tm); return mute_type & (1 << now_tm.tm_wday); }
kernel_zalloc_check(app_name_attr->length + 1)
<|repo_name|>pebble <|file_sep|>src/fw/services/normal/notifications/ancs/ancs_filtering.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ancs_filtering.h" #include "drivers/rtc.h" #include "kernel/pbl_malloc.h" #include "services/normal/notifications/alerts_preferences.h" #include "services/normal/timeline/attributes_actions.h" #include "system/logging.h" #include "util/pstring.h" void ancs_filtering_record_app(iOSNotifPrefs **notif_prefs, const ANCSAttribute *app_id, const ANCSAttribute *display_name, const ANCSAttribute *title) { // When we receive a notification, information about the app that sent us the notification // is recorded in the notif_pref_db. We sync this DB with the phone which allows us to // do things like add non ANCS actions, or filter notifications by app // The "default" attributes are merged with any existing attributes. This makes it easy to add // new attributes in the future as well as support EMail / SMS apps which already have data // stored. iOSNotifPrefs *app_notif_prefs = *notif_prefs; const int num_existing_attribtues = app_notif_prefs ? app_notif_prefs->attr_list.num_attributes : 0; AttributeList new_attr_list; attribute_list_init_list(num_existing_attribtues, &new_attr_list); bool list_dirty = false; // Copy over all the existing attributes to our new list if (app_notif_prefs) { for (int i = 0; i < num_existing_attribtues; i++) { new_attr_list.attributes[i] = app_notif_prefs->attr_list.attributes[i]; } } // The app name should be the display name // If there is no display name (Apple Pay) then fallback to the title const ANCSAttribute *app_name_attr = NULL; if (display_name && display_name->length > 0) { app_name_attr = display_name; } else if (title && title->length > 0) { app_name_attr = title; } char *app_name_buff = NULL; if (app_name_attr) { const char *existing_name = ""; if (app_notif_prefs) { existing_name = attribute_get_string(&app_notif_prefs->attr_list, AttributeIdAppName, ""); } if (!pstring_equal_cstring(&app_name_attr->pstr, existing_name)) { // If the existing name doesn't match our new name, update the name app_name_buff = <|fim_suffix|>; pstring_pstring16_to_string(&app_name_attr->pstr, app_name_buff); attribute_list_add_cstring(&new_attr_list, AttributeIdAppName, app_name_buff); list_dirty = true; PBL_LOG(LOG_LEVEL_INFO, "Adding app name to app prefs: <%s>", app_name_buff); } } // Add the mute attribute if we don't have one already // Default the app to not muted const bool already_has_mute = app_notif_prefs && attribute_find(&app_notif_prefs->attr_list, AttributeIdMuteDayOfWeek); if (!already_has_mute) { attribute_list_add_uint8(&new_attr_list, AttributeIdMuteDayOfWeek, MuteBitfield_None); list_dirty = true; } // Add / update the "last seen" timestamp Attribute *last_updated = NULL; if (app_notif_prefs) { last_updated = attribute_find(&app_notif_prefs->attr_list, AttributeIdLastUpdated); } uint32_t now = rtc_get_time(); // Only perform an update if there is no timestamp or the current timestamp is more than a day old if (!last_updated || (last_updated && now > (last_updated->uint32 + SECONDS_PER_DAY))) { attribute_list_add_uint32(&new_attr_list, AttributeIdLastUpdated, now); list_dirty = true; PBL_LOG(LOG_LEVEL_INFO, "Updating / adding timestamp to app prefs"); } if (list_dirty) { // We don't change or add actions at this time TimelineItemActionGroup *new_action_group = NULL; if (app_notif_prefs) { new_action_group = &app_notif_prefs->action_group; } ios_notif_pref_db_store_prefs(app_id->value, app_id->length, &new_attr_list, new_action_group); // Update our copy of the prefs with the new data const size_t buf_size = attributes_actions_get_buffer_size(&new_attr_list, new_action_group); *notif_prefs = kernel_zalloc_check(sizeof(iOSNotifPrefs) + buf_size); uint8_t *buffer = (uint8_t*)*notif_prefs + sizeof(iOSNotifPrefs); attributes_actions_deep_copy(&new_attr_list, &(*notif_prefs)->attr_list, new_action_group, &(*notif_prefs)->action_group, buffer, buffer + buf_size); ios_notif_pref_db_free_prefs(app_notif_prefs); } kernel_free(app_name_buff); attribute_list_destroy_list(&new_attr_list); } uint8_t ancs_filtering_get_mute_type(const iOSNotifPrefs *app_notif_prefs) { if (app_notif_prefs) { return attribute_get_uint8(&app_notif_prefs->attr_list, AttributeIdMuteDayOfWeek, MuteBitfield_None); } return MuteBitfield_None; } bool ancs_filtering_is_muted(const iOSNotifPrefs *app_notif_prefs) { uint8_t mute_type = ancs_filtering_get_mute_type(app_notif_prefs); struct tm now_tm; time_t now = rtc_get_time(); localtime_r(&now, &now_tm); return mute_type & (1 << now_tm.tm_wday); } <|fim_middle|>kernel_zalloc_check(app_name_attr->length + 1)<|endoftext|>
masked_node
argument_list
tests/fw/graphics/test_graphics_draw_rect.template.c
ross_x_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_across_x_offset_layer.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_nx_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_across_nx_offset_layer.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_y_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_across_y_offset_layer.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_ny_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_across_ny_offset_layer.${BIT_DEPTH_NAME}.pbi")); } void test_graphics_draw_rect_${BIT_DEPTH_NAME}__color(void) { GContext ctx; Layer layer; test_graphics_context_init(&ctx, fb); layer_init(&layer, &GRect(0, 0, 20, 10)); layer_set_update_proc(&layer, &inside_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_inside_origin_layer.${BIT_DEPTH_NAME}.pbi")); layer_set_update_proc(&layer, &white_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(framebuffer_is_empty("white_over_black", ctx.parent_framebuffer, GColorWhite)); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &inside_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_inside_origin_layer.${BIT_DEPTH_NAME}.pbi")); layer_set_update_proc(&layer, &clear_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(framebuffer_is_empty("clear_over_black", ctx.parent_framebuffer, GColorWhite)); } #define ORIGIN_RECT_NO_CLIP GRect(0, 0, 144, 168) #define ORIGIN_RECT_CLIP_XY GRect(0, 0, 20, 20) #define ORIGIN_RECT_CLIP_NXNY GRect(0, 0, 144, 168) #define ORIGIN_DRAW_RECT_NO_CLIP GRect(6, 6, 30, 40) #define ORIGIN_DRAW_RECT_CLIP_XY GRect(6, 6, 30, 40) #define ORIGIN_DRAW_RECT_CLIP_NXNY GRect(-16, -16, 30, 40) void test_graphics_draw_rect_${BIT_DEPTH_NAME}__origin_aa_sw(void) { GContext ctx; test_graphics_context_init(&ctx, fb); // AA = true, SW = 1 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, true, 1); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw1_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, true, 1); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw1_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, true, 1); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw1_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // AA = true, SW = 2 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, true, 2); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw2_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, true, 2); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw2_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, true, 2); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw2_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // AA = true, SW = 3 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, true, 3); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check
; setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, true, 3); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw3_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, true, 3); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw3_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 // AA = true, SW = 4 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, true, 4); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw4_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, true, 4); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw4_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, true, 4); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw4_clip_nxny.${BIT_DEPTH_NAME}.pbi")); #endif // AA = true, SW = 5 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, true, 5); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw5_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, true, 5); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw5_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, true, 5); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw5_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 // AA = true, SW = 11 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, true, 11); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, true, 11); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw11_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, true, 11); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw11_clip_nxny.${BIT_DEPTH_NAME}.pbi")); #endif } void test_graphics_draw_rect_${BIT_DEPTH_NAME}__origin_sw(void) { GContext ctx; test_graphics_context_init(&ctx, fb); // SW = 1 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 1); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_sw1_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, false, 1); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_sw1_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, false, 1); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_sw1_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // SW = 2 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 2); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_sw2_no_clip.${
(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw3_no_clip.${BIT_DEPTH_NAME}.pbi"))
<|repo_name|>pebble <|file_sep|>tests/fw/graphics/test_graphics_draw_rect.template.c <|fim_prefix|>ross_x_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_across_x_offset_layer.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_nx_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_across_nx_offset_layer.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_y_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_across_y_offset_layer.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &across_ny_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_across_ny_offset_layer.${BIT_DEPTH_NAME}.pbi")); } void test_graphics_draw_rect_${BIT_DEPTH_NAME}__color(void) { GContext ctx; Layer layer; test_graphics_context_init(&ctx, fb); layer_init(&layer, &GRect(0, 0, 20, 10)); layer_set_update_proc(&layer, &inside_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_inside_origin_layer.${BIT_DEPTH_NAME}.pbi")); layer_set_update_proc(&layer, &white_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(framebuffer_is_empty("white_over_black", ctx.parent_framebuffer, GColorWhite)); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &inside_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_inside_origin_layer.${BIT_DEPTH_NAME}.pbi")); layer_set_update_proc(&layer, &clear_layer_update_callback); layer_render_tree(&layer, &ctx); cl_check(framebuffer_is_empty("clear_over_black", ctx.parent_framebuffer, GColorWhite)); } #define ORIGIN_RECT_NO_CLIP GRect(0, 0, 144, 168) #define ORIGIN_RECT_CLIP_XY GRect(0, 0, 20, 20) #define ORIGIN_RECT_CLIP_NXNY GRect(0, 0, 144, 168) #define ORIGIN_DRAW_RECT_NO_CLIP GRect(6, 6, 30, 40) #define ORIGIN_DRAW_RECT_CLIP_XY GRect(6, 6, 30, 40) #define ORIGIN_DRAW_RECT_CLIP_NXNY GRect(-16, -16, 30, 40) void test_graphics_draw_rect_${BIT_DEPTH_NAME}__origin_aa_sw(void) { GContext ctx; test_graphics_context_init(&ctx, fb); // AA = true, SW = 1 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, true, 1); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw1_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, true, 1); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw1_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, true, 1); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw1_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // AA = true, SW = 2 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, true, 2); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw2_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, true, 2); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw2_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, true, 2); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw2_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // AA = true, SW = 3 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, true, 3); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check<|fim_suffix|>; setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, true, 3); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw3_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, true, 3); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw3_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 // AA = true, SW = 4 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, true, 4); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw4_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, true, 4); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw4_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, true, 4); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw4_clip_nxny.${BIT_DEPTH_NAME}.pbi")); #endif // AA = true, SW = 5 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, true, 5); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw5_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, true, 5); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw5_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, true, 5); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw5_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // TODO: Fix offset calculation and reenable this: - PBL-16509 #if SCREEN_COLOR_DEPTH_BITS == 8 // AA = true, SW = 11 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, true, 11); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw11_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, true, 11); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw11_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, true, 11); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw11_clip_nxny.${BIT_DEPTH_NAME}.pbi")); #endif } void test_graphics_draw_rect_${BIT_DEPTH_NAME}__origin_sw(void) { GContext ctx; test_graphics_context_init(&ctx, fb); // SW = 1 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 1); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_sw1_no_clip.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_XY, ORIGIN_RECT_CLIP_XY, false, 1); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_XY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_sw1_clip_xy.${BIT_DEPTH_NAME}.pbi")); setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_CLIP_NXNY, ORIGIN_RECT_CLIP_NXNY, false, 1); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_CLIP_NXNY); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_sw1_clip_nxny.${BIT_DEPTH_NAME}.pbi")); // SW = 2 setup_test_aa_sw(&ctx, fb, ORIGIN_RECT_NO_CLIP, ORIGIN_RECT_NO_CLIP, false, 2); graphics_draw_rect(&ctx, &ORIGIN_DRAW_RECT_NO_CLIP); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_sw2_no_clip.${<|fim_middle|>(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_rect_origin_aa_sw3_no_clip.${BIT_DEPTH_NAME}.pbi"))<|endoftext|>
masked_node
argument_list
src/fw/applib/pbl_std/strftime.c
if (left <= length) { goto _out_of_size; } memcpy(dest_str, fmt, length); dest_str += length; left -= length; fmt = ptr + 1; // End of string if (*ptr == '\0' || *fmt == '\0') { break; } char pad = '\0'; size_t width = 0; // Process flags // These are the only ones our old impl cared about. if (*fmt == '0' || *fmt == '+') { pad = *fmt++; } // Process field width if (*fmt >= '1' && *fmt <= '9') { width = strtol(fmt, &ptr, 10); fmt = ptr; } // Process modifiers (SU) if (*fmt == 'E' || *fmt == 'O') { // We just drop them on the floor. Uh oh spaghetti-o // Not like the old implementation really did them either. fmt++; } // Helper macros to make goto stuff look cleaner #define FMT_STRCOPY(V) do { \ i18nstr = NULL; \ cpystr = V; \ goto _fmt_strcopy; \ } while (0) #define FMT_STRCOPY_I18N(V) do { \ i18nstr = V; \ goto _fmt_strcopy; \ } while (0) #define FMT_INTCOPY(V, L, F) do { \ cpyint_val = V; \ cpyint_len = L; \ cpyint_flag = F; \ goto _fmt_intcopy; \ } while (0) #define FMT_RECURSE(FMT) do { \ i18nstr = NULL; \ cpystr = FMT; \ goto _fmt_recurse; \ } while (0) #define FMT_RECURSE_I18N(FMT) do { \ i18nstr = FMT; \ goto _fmt_recurse; \ } while (0) // Terrible local state for goto hell const char *cpystr = NULL; const char *i18nstr; int cpyint_val; size_t cpyint_len; unsigned int cpyint_flag; // Process conversion specifiers switch (*fmt) { case 'a': FMT_STRCOPY_I18N(time_locale->wday[t->tm_wday % DAYS_PER_WEEK]); _fmt_strcopy: // old strftime doesn't use 'width' for strings if (!use_i18n && i18nstr) { cpystr = i18nstr; i18nstr = NULL; } if (i18nstr) { length = sys_i18n_get_length(i18nstr); } else { length = strlen(cpystr); } if (left <= length) { goto _out_of_size; } if (i18nstr) { sys_i18n_get_with_buffer(i18nstr, dest_str, length + 1); } else { memcpy(dest_str, cpystr, length); } dest_str += length; left -= length; break; case 'A': FMT_STRCOPY_I18N(time_locale->weekday[t->tm_wday % DAYS_PER_WEEK]); break; case 'h': // SU case 'b': FMT_STRCOPY_I18N(time_locale->mon[t->tm_mon % MONTHS_PER_YEAR]); break; case 'B': FMT_STRCOPY_I18N(time_locale->month[t->tm_mon % MONTHS_PER_YEAR]); break; case 'c': FMT_RECURSE_I18N(time_locale->c_fmt); _fmt_recurse: if (!use_i18n && i18nstr) { cpystr = i18nstr; i18nstr = NULL; } if (i18nstr) { cpystr = i18n_get(i18nstr, dest_str); } length = localized_strftime(dest_str, left, cpystr, t, locale); if (i18nstr) { i18n_free(i18nstr, dest_str); } if (length == 0) { goto _out_of_size; } dest_str += length; left -= length; break; case 'C': // SU FMT_INTCOPY(year / 100, 2, INTFMT_PADZERO); _fmt_intcopy: { const char *intfmt; if (pad != '\0' || cpyint_flag == INTFMT_PADZERO) { intfmt = "%0*d"; } else { intfmt = "%*d"; } width = MAX(width, cpyint_len); length = snprintf(NULL, 0, intfmt, width, cpyint_val); if (left <= length) { goto _out_of_size; } sprintf(dest_str, intfmt, width, cpyint_val); dest_str += length; left -= length; } break; case 'd': FMT_INTCOPY(t->tm_mday, 2, INTFMT_PADZERO); break; case 'D': // SU FMT_RECURSE("%m/%d/%y"); break; case 'e': // SU FMT_INTCOPY(t->tm_mday, 2, INTFMT_PADSPACE); break; case 'F': // C99 FMT_RECURSE("%Y-%m-%d"); break; case 'g': // TZ FMT_INTCOPY
; break; case 'G': // TZ FMT_INTCOPY(prv_iso8601_year(t), 4, INTFMT_PADZERO); break; case 'H': FMT_INTCOPY(t->tm_hour, 2, INTFMT_PADZERO); break; case 'I': FMT_INTCOPY(hour_12h, 2, INTFMT_PADZERO); break; case 'j': FMT_INTCOPY(t->tm_yday+1, 3, INTFMT_PADZERO); break; case 'k': // TZ FMT_INTCOPY(t->tm_hour, 2, INTFMT_PADSPACE); break; case 'l': // TZ FMT_INTCOPY(hour_12h, 2, INTFMT_PADSPACE); break; case 'm': FMT_INTCOPY(t->tm_mon + 1, 2, INTFMT_PADZERO); break; case 'M': FMT_INTCOPY(t->tm_min, 2, INTFMT_PADZERO); break; case 'r': // SU FMT_RECURSE_I18N(time_locale->r_fmt); break; case 'p': if (t->tm_hour < 12) { FMT_STRCOPY_I18N(time_locale->am_pm_upcase[0]); } else { FMT_STRCOPY_I18N(time_locale->am_pm_upcase[1]); } break; case 'P': // GNU if (t->tm_hour < 12) { FMT_STRCOPY_I18N(time_locale->am_pm_downcase[0]); } else { FMT_STRCOPY_I18N(time_locale->am_pm_downcase[1]); } break; case 'R': // SU FMT_RECURSE("%H:%M"); break; case 'S': FMT_INTCOPY(t->tm_sec, 2, INTFMT_PADZERO); break; case 'T': // SU FMT_RECURSE("%H:%M:%S"); break; case 'u': // SU if (t->tm_wday == 0) { FMT_INTCOPY(7, 1, INTFMT_PADZERO); break; } // fall-thru case 'w': FMT_INTCOPY(t->tm_wday, 1, INTFMT_PADZERO); break; case 'U': // Week starting on Sunday FMT_INTCOPY(prv_week_of_year(t, false), 2, INTFMT_PADZERO); break; case 'V': // SU FMT_INTCOPY(prv_iso8601_week(t), 2, INTFMT_PADZERO); break; case 'W': // Week starting on Monday, like savages FMT_INTCOPY(prv_week_of_year(t, true), 2, INTFMT_PADZERO); break; case 'x': FMT_RECURSE_I18N(time_locale->x_fmt); break; case 'X': FMT_RECURSE_I18N(time_locale->X_fmt); break; case 'y': FMT_INTCOPY(year % 100, 2, INTFMT_PADZERO); break; case 'Y': FMT_INTCOPY(year, 4, INTFMT_PADZERO); break; case 'z': { if (left < 5) { goto _out_of_size; } sprintf(dest_str, "%+.2d%02u", t->tm_gmtoff / 3600, (abs(t->tm_gmtoff) / 60) % 60); dest_str += 5; left -= 5; break; } case 'Z': FMT_STRCOPY(t->tm_zone); break; case 'n': // SU *dest_str++ = '\n'; goto _fmt_chcopy; case 't': // SU *dest_str++ = '\t'; goto _fmt_chcopy; // Copy stuff case '%': *dest_str++ = '%'; _fmt_chcopy: left--; break; case 's': // TZ // Old implementation didn't have it, skip it for code size. case '+': // TZ // Old implementation didn't have it, skip it for code size. default: // Old implementation just ignores invalid specifiers break; } fmt++; } if (left == 0) { goto _out_of_size; } // Finish him!! dest_str[0] = '\0'; return maxsize - left; _out_of_size: // Oops we're dead return 0; } size_t strftime(char * restrict s, size_t maxsize, const char* format, const struct tm* tim_p) { // Pass a NULL locale because firmware strftime is always localized return localized_strftime(s, maxsize, format, tim_p, NULL); }
(prv_iso8601_year(t) % 100, 2, INTFMT_PADZERO)
<|repo_name|>pebble <|file_sep|>src/fw/applib/pbl_std/strftime.c <|fim_prefix|> if (left <= length) { goto _out_of_size; } memcpy(dest_str, fmt, length); dest_str += length; left -= length; fmt = ptr + 1; // End of string if (*ptr == '\0' || *fmt == '\0') { break; } char pad = '\0'; size_t width = 0; // Process flags // These are the only ones our old impl cared about. if (*fmt == '0' || *fmt == '+') { pad = *fmt++; } // Process field width if (*fmt >= '1' && *fmt <= '9') { width = strtol(fmt, &ptr, 10); fmt = ptr; } // Process modifiers (SU) if (*fmt == 'E' || *fmt == 'O') { // We just drop them on the floor. Uh oh spaghetti-o // Not like the old implementation really did them either. fmt++; } // Helper macros to make goto stuff look cleaner #define FMT_STRCOPY(V) do { \ i18nstr = NULL; \ cpystr = V; \ goto _fmt_strcopy; \ } while (0) #define FMT_STRCOPY_I18N(V) do { \ i18nstr = V; \ goto _fmt_strcopy; \ } while (0) #define FMT_INTCOPY(V, L, F) do { \ cpyint_val = V; \ cpyint_len = L; \ cpyint_flag = F; \ goto _fmt_intcopy; \ } while (0) #define FMT_RECURSE(FMT) do { \ i18nstr = NULL; \ cpystr = FMT; \ goto _fmt_recurse; \ } while (0) #define FMT_RECURSE_I18N(FMT) do { \ i18nstr = FMT; \ goto _fmt_recurse; \ } while (0) // Terrible local state for goto hell const char *cpystr = NULL; const char *i18nstr; int cpyint_val; size_t cpyint_len; unsigned int cpyint_flag; // Process conversion specifiers switch (*fmt) { case 'a': FMT_STRCOPY_I18N(time_locale->wday[t->tm_wday % DAYS_PER_WEEK]); _fmt_strcopy: // old strftime doesn't use 'width' for strings if (!use_i18n && i18nstr) { cpystr = i18nstr; i18nstr = NULL; } if (i18nstr) { length = sys_i18n_get_length(i18nstr); } else { length = strlen(cpystr); } if (left <= length) { goto _out_of_size; } if (i18nstr) { sys_i18n_get_with_buffer(i18nstr, dest_str, length + 1); } else { memcpy(dest_str, cpystr, length); } dest_str += length; left -= length; break; case 'A': FMT_STRCOPY_I18N(time_locale->weekday[t->tm_wday % DAYS_PER_WEEK]); break; case 'h': // SU case 'b': FMT_STRCOPY_I18N(time_locale->mon[t->tm_mon % MONTHS_PER_YEAR]); break; case 'B': FMT_STRCOPY_I18N(time_locale->month[t->tm_mon % MONTHS_PER_YEAR]); break; case 'c': FMT_RECURSE_I18N(time_locale->c_fmt); _fmt_recurse: if (!use_i18n && i18nstr) { cpystr = i18nstr; i18nstr = NULL; } if (i18nstr) { cpystr = i18n_get(i18nstr, dest_str); } length = localized_strftime(dest_str, left, cpystr, t, locale); if (i18nstr) { i18n_free(i18nstr, dest_str); } if (length == 0) { goto _out_of_size; } dest_str += length; left -= length; break; case 'C': // SU FMT_INTCOPY(year / 100, 2, INTFMT_PADZERO); _fmt_intcopy: { const char *intfmt; if (pad != '\0' || cpyint_flag == INTFMT_PADZERO) { intfmt = "%0*d"; } else { intfmt = "%*d"; } width = MAX(width, cpyint_len); length = snprintf(NULL, 0, intfmt, width, cpyint_val); if (left <= length) { goto _out_of_size; } sprintf(dest_str, intfmt, width, cpyint_val); dest_str += length; left -= length; } break; case 'd': FMT_INTCOPY(t->tm_mday, 2, INTFMT_PADZERO); break; case 'D': // SU FMT_RECURSE("%m/%d/%y"); break; case 'e': // SU FMT_INTCOPY(t->tm_mday, 2, INTFMT_PADSPACE); break; case 'F': // C99 FMT_RECURSE("%Y-%m-%d"); break; case 'g': // TZ FMT_INTCOPY<|fim_suffix|>; break; case 'G': // TZ FMT_INTCOPY(prv_iso8601_year(t), 4, INTFMT_PADZERO); break; case 'H': FMT_INTCOPY(t->tm_hour, 2, INTFMT_PADZERO); break; case 'I': FMT_INTCOPY(hour_12h, 2, INTFMT_PADZERO); break; case 'j': FMT_INTCOPY(t->tm_yday+1, 3, INTFMT_PADZERO); break; case 'k': // TZ FMT_INTCOPY(t->tm_hour, 2, INTFMT_PADSPACE); break; case 'l': // TZ FMT_INTCOPY(hour_12h, 2, INTFMT_PADSPACE); break; case 'm': FMT_INTCOPY(t->tm_mon + 1, 2, INTFMT_PADZERO); break; case 'M': FMT_INTCOPY(t->tm_min, 2, INTFMT_PADZERO); break; case 'r': // SU FMT_RECURSE_I18N(time_locale->r_fmt); break; case 'p': if (t->tm_hour < 12) { FMT_STRCOPY_I18N(time_locale->am_pm_upcase[0]); } else { FMT_STRCOPY_I18N(time_locale->am_pm_upcase[1]); } break; case 'P': // GNU if (t->tm_hour < 12) { FMT_STRCOPY_I18N(time_locale->am_pm_downcase[0]); } else { FMT_STRCOPY_I18N(time_locale->am_pm_downcase[1]); } break; case 'R': // SU FMT_RECURSE("%H:%M"); break; case 'S': FMT_INTCOPY(t->tm_sec, 2, INTFMT_PADZERO); break; case 'T': // SU FMT_RECURSE("%H:%M:%S"); break; case 'u': // SU if (t->tm_wday == 0) { FMT_INTCOPY(7, 1, INTFMT_PADZERO); break; } // fall-thru case 'w': FMT_INTCOPY(t->tm_wday, 1, INTFMT_PADZERO); break; case 'U': // Week starting on Sunday FMT_INTCOPY(prv_week_of_year(t, false), 2, INTFMT_PADZERO); break; case 'V': // SU FMT_INTCOPY(prv_iso8601_week(t), 2, INTFMT_PADZERO); break; case 'W': // Week starting on Monday, like savages FMT_INTCOPY(prv_week_of_year(t, true), 2, INTFMT_PADZERO); break; case 'x': FMT_RECURSE_I18N(time_locale->x_fmt); break; case 'X': FMT_RECURSE_I18N(time_locale->X_fmt); break; case 'y': FMT_INTCOPY(year % 100, 2, INTFMT_PADZERO); break; case 'Y': FMT_INTCOPY(year, 4, INTFMT_PADZERO); break; case 'z': { if (left < 5) { goto _out_of_size; } sprintf(dest_str, "%+.2d%02u", t->tm_gmtoff / 3600, (abs(t->tm_gmtoff) / 60) % 60); dest_str += 5; left -= 5; break; } case 'Z': FMT_STRCOPY(t->tm_zone); break; case 'n': // SU *dest_str++ = '\n'; goto _fmt_chcopy; case 't': // SU *dest_str++ = '\t'; goto _fmt_chcopy; // Copy stuff case '%': *dest_str++ = '%'; _fmt_chcopy: left--; break; case 's': // TZ // Old implementation didn't have it, skip it for code size. case '+': // TZ // Old implementation didn't have it, skip it for code size. default: // Old implementation just ignores invalid specifiers break; } fmt++; } if (left == 0) { goto _out_of_size; } // Finish him!! dest_str[0] = '\0'; return maxsize - left; _out_of_size: // Oops we're dead return 0; } size_t strftime(char * restrict s, size_t maxsize, const char* format, const struct tm* tim_p) { // Pass a NULL locale because firmware strftime is always localized return localized_strftime(s, maxsize, format, tim_p, NULL); } <|fim_middle|>(prv_iso8601_year(t) % 100, 2, INTFMT_PADZERO)<|endoftext|>
masked_node
call_expression
tests/fw/util/test_hdlc.c
lcStreamingContext ctx; hdlc_streaming_decode_reset(&ctx); for (int i = 0; i < len; i++) { char c = str[i]; bool should_store, is_invalid; bool is_complete = hdlc_streaming_decode(&ctx, (uint8_t *)&c, &should_store, &is_invalid); cl_assert(is_invalid == false); if (i == 0 || i == len - 1) { cl_assert(is_complete == true); cl_assert(should_store == false); } else { cl_assert(is_complete == false); cl_assert(should_store == true); cl_assert(c == str[i]); } } } void test_hdlc__special_characters(void) { // make sure the escape characters haven't changed cl_assert(HDLC_FLAG == 0x7e); cl_assert(HDLC_ESCAPE == 0x7d); cl_assert(HDLC_ESCAPE_MASK == 0x20); } void test_hdlc__decode_empty(void) { // consecutive empty frames const uint8_t str[4] = {HDLC_FLAG, HDLC_FLAG, HDLC_FLAG, HDLC_FLAG}; HdlcStreamingContext ctx; hdlc_streaming_decode_reset(&ctx); for (int i = 0; i < 4; i++) { char c = str[i]; bool should_store, is_invalid; bool is_complete = hdlc_streaming_decode(&ctx, (uint8_t *)&c, &should_store, &is_invalid); cl_assert(is_complete == true); cl_assert(should_store == false); cl_assert(is_invalid == false); } } void test_hdlc__decode_invalid(void) { // invalid sequences uint8_t data; bool should_store, is_invalid, is_complete; HdlcStreamingContext ctx; // two consecutive escape characters hdlc_streaming_decode_reset(&ctx); data = HDLC_ESCAPE; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == false); cl_assert(is_invalid == false); data = HDLC_ESCAPE; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == false); cl_assert(is_invalid == true); // an escape character followed by a flag hdlc_streaming_decode_reset(&ctx); data = HDLC_ESCAPE; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == false); cl_assert(is_invalid == false); data = HDLC_FLAG; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == true); cl_assert(should_store == false); cl_assert(is_invalid == true); } void test_hdlc__decode_escaped_special(void) { // 2 escaped special characters uint8_t data; bool should_store, is_invalid, is_complete; HdlcStreamingContext ctx; hdlc_streaming_decode_reset(&ctx); // escaped escape character data = HDLC_ESCAPE; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == false); cl_assert(is_invalid == false); data = HDLC_ESCAPE ^ HDLC_ESCAPE_MASK; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == true); cl_assert(is_invalid == false); cl_assert(data == HDLC_ESCAPE); // escaped flag data = HDLC_ESCAPE; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == false); cl_assert(is_invalid == false); data = HDLC_FLAG ^ HDLC_ESCAPE_MASK; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == true); cl_assert(is_invalid == false); cl_assert(data == HDLC_FLAG); } void test_hdlc__encode_decode(void) { const char *str = "this is a string with the special \x7e \x7d \x7e\x7d \x7d\x7e characters"; char buffer[100]; int write_idx = 0; for (int i = 0; i < strlen(str); i++) { char c = str[i]; if (hdlc_encode((uint8_t *)&c)) { buffer[write_idx++] = HDLC_ESCAPE; } buffer[write_idx++] = c; } buffer[write_idx++] = HDLC_FLAG; cl_assert(write_idx == strlen(str) + 7 /* 6 special characters to escape + 1 flag at end */); HdlcStreamingContext ctx;
; int read_idx = 0; int i = 0; while (true) { char c = buffer[i++]; bool should_store, is_invalid; bool is_complete = hdlc_streaming_decode(&ctx, (uint8_t *)&c, &should_store, &is_invalid); cl_assert(is_invalid == false); if (should_store) { cl_assert(is_complete == false); cl_assert(c == str[read_idx++]); } if (is_complete) { cl_assert(should_store == false); cl_assert(i == write_idx); break; } } cl_assert(read_idx == strlen(str)); }
hdlc_streaming_decode_reset(&ctx)
<|repo_name|>pebble <|file_sep|>tests/fw/util/test_hdlc.c <|fim_prefix|>lcStreamingContext ctx; hdlc_streaming_decode_reset(&ctx); for (int i = 0; i < len; i++) { char c = str[i]; bool should_store, is_invalid; bool is_complete = hdlc_streaming_decode(&ctx, (uint8_t *)&c, &should_store, &is_invalid); cl_assert(is_invalid == false); if (i == 0 || i == len - 1) { cl_assert(is_complete == true); cl_assert(should_store == false); } else { cl_assert(is_complete == false); cl_assert(should_store == true); cl_assert(c == str[i]); } } } void test_hdlc__special_characters(void) { // make sure the escape characters haven't changed cl_assert(HDLC_FLAG == 0x7e); cl_assert(HDLC_ESCAPE == 0x7d); cl_assert(HDLC_ESCAPE_MASK == 0x20); } void test_hdlc__decode_empty(void) { // consecutive empty frames const uint8_t str[4] = {HDLC_FLAG, HDLC_FLAG, HDLC_FLAG, HDLC_FLAG}; HdlcStreamingContext ctx; hdlc_streaming_decode_reset(&ctx); for (int i = 0; i < 4; i++) { char c = str[i]; bool should_store, is_invalid; bool is_complete = hdlc_streaming_decode(&ctx, (uint8_t *)&c, &should_store, &is_invalid); cl_assert(is_complete == true); cl_assert(should_store == false); cl_assert(is_invalid == false); } } void test_hdlc__decode_invalid(void) { // invalid sequences uint8_t data; bool should_store, is_invalid, is_complete; HdlcStreamingContext ctx; // two consecutive escape characters hdlc_streaming_decode_reset(&ctx); data = HDLC_ESCAPE; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == false); cl_assert(is_invalid == false); data = HDLC_ESCAPE; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == false); cl_assert(is_invalid == true); // an escape character followed by a flag hdlc_streaming_decode_reset(&ctx); data = HDLC_ESCAPE; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == false); cl_assert(is_invalid == false); data = HDLC_FLAG; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == true); cl_assert(should_store == false); cl_assert(is_invalid == true); } void test_hdlc__decode_escaped_special(void) { // 2 escaped special characters uint8_t data; bool should_store, is_invalid, is_complete; HdlcStreamingContext ctx; hdlc_streaming_decode_reset(&ctx); // escaped escape character data = HDLC_ESCAPE; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == false); cl_assert(is_invalid == false); data = HDLC_ESCAPE ^ HDLC_ESCAPE_MASK; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == true); cl_assert(is_invalid == false); cl_assert(data == HDLC_ESCAPE); // escaped flag data = HDLC_ESCAPE; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == false); cl_assert(is_invalid == false); data = HDLC_FLAG ^ HDLC_ESCAPE_MASK; is_complete = hdlc_streaming_decode(&ctx, &data, &should_store, &is_invalid); cl_assert(is_complete == false); cl_assert(should_store == true); cl_assert(is_invalid == false); cl_assert(data == HDLC_FLAG); } void test_hdlc__encode_decode(void) { const char *str = "this is a string with the special \x7e \x7d \x7e\x7d \x7d\x7e characters"; char buffer[100]; int write_idx = 0; for (int i = 0; i < strlen(str); i++) { char c = str[i]; if (hdlc_encode((uint8_t *)&c)) { buffer[write_idx++] = HDLC_ESCAPE; } buffer[write_idx++] = c; } buffer[write_idx++] = HDLC_FLAG; cl_assert(write_idx == strlen(str) + 7 /* 6 special characters to escape + 1 flag at end */); HdlcStreamingContext ctx; <|fim_suffix|>; int read_idx = 0; int i = 0; while (true) { char c = buffer[i++]; bool should_store, is_invalid; bool is_complete = hdlc_streaming_decode(&ctx, (uint8_t *)&c, &should_store, &is_invalid); cl_assert(is_invalid == false); if (should_store) { cl_assert(is_complete == false); cl_assert(c == str[read_idx++]); } if (is_complete) { cl_assert(should_store == false); cl_assert(i == write_idx); break; } } cl_assert(read_idx == strlen(str)); } <|fim_middle|>hdlc_streaming_decode_reset(&ctx)<|endoftext|>
masked_node
call_expression
tests/fw/services/activity/test_workout_service.c
-- // Open the app, start a workout, close the app. Make sure the HR stays on for // WORKOUT_ACTIVE_HR_SUBSCRIPTION_TS_EXPIRE void test_workout_service__app_open_close_active_workout(void) { // Put some time into the clock prv_inc_time(1 * SECONDS_PER_MINUTE); // Open the app, confirm that we are now subscribed with no end in sight workout_service_frontend_opened(); cl_assert_equal_b(s_hrm_subscribed, true); cl_assert_equal_i(s_hrm_expiration, 0); cl_assert(workout_service_start_workout(ActivitySessionType_Run)); workout_service_frontend_closed(); cl_assert_equal_b(s_hrm_subscribed, true); cl_assert_equal_i(s_hrm_expiration, SECONDS_PER_HOUR); } // --------------------------------------------------------------------------------------- // Open the app, start a workout, 30s, stop the workout. Make sure the HR turns off instantly // since workout wasn't valid (too short) void test_workout_service__app_open_close_ended_invalid_workout(void) { // Put some time into the clock prv_inc_time(1 * SECONDS_PER_MINUTE); // Open the app, confirm that we are now subscribed with no end in sight workout_service_frontend_opened(); cl_assert_equal_b(s_hrm_subscribed, true); cl_assert_equal_i(s_hrm_expiration, 0); prv_inc_time(1 * SECONDS_PER_MINUTE); cl_assert(workout_service_start_workout(ActivitySessionType_Run)); // Workout of 30 seconds duration. Should be invalid, not keep HR on after leaving prv_inc_time(30); cl_assert(workout_service_stop_workout()); workout_service_frontend_closed(); cl_assert_equal_b(s_hrm_subscribed, false); cl_assert_equal_i(s_hrm_expiration, 0); } // --------------------------------------------------------------------------------------- // Open the app, start a workout, 120s, stop the workout, 120s, close app. // Make sure the HR stays on for WORKOUT_ENDED_HR_SUBSCRIPTION_TS_EXPIRE - 120s void test_workout_service__app_open_close_valid_workout(void) { // Put some time into the clock prv_inc_time(1 * SECONDS_PER_MINUTE); // Open the app, confirm that we are now subscribed with no end in sight workout_service_frontend_opened(); cl_assert_equal_b(s_hrm_subscribed, true); cl_assert_equal_i(s_hrm_expiration, 0); prv_inc_time(1 * SECONDS_PER_MINUTE); cl_assert(workout_service_start_workout(ActivitySessionType_Run)); // Workout of 120 seconds duration. Should be valid prv_inc_time(2 * SECONDS_PER_MINUTE); cl_assert(workout_service_stop_workout()); prv_inc_time(2 * SECONDS_PER_MINUTE); workout_service_frontend_closed(); cl_assert_equal_b(s_hrm_subscribed, true); cl_assert_equal_i(s_hrm_expiration, 8 * SECONDS_PER_MINUTE); } // --------------------------------------------------------------------------------------- // Open the app, start a workout, 120s, stop the workout, 20 min, close app. // Make sure the HR turns off right after we leave the app. void test_workout_service__app_open_wait_close_valid_workout(void) { // Put some time into the clock prv_inc_time(1 * SECONDS_PER_MINUTE); // Open the app, confirm that we are now subscribed with no end in sight workout_service_frontend_opened(); cl_assert_equal_b(s_hrm_subscribed, true); cl_assert_equal_i(s_hrm_expiration, 0); prv_inc_time(1 * SECONDS_PER_MINUTE); cl_assert(workout_service_start_workout(ActivitySessionType_Run)); // Workout of 120 seconds duration. Should be valid prv_inc_time(2 * SECONDS_PER_MINUTE); cl_assert(workout_service_stop_workout()); // Wait 20 minutes. By this time, as soon as we leave the app, we should turn off the HR device. prv_inc_time(20 * SECONDS_PER_MINUTE); workout_service_frontend_closed(); cl_assert_equal_b(s_hrm_subscribed, false); cl_assert_equal_i(s_hrm_expiration, 0); } // --------------------------------------------------------------------------------------- void test_workout_service__heart_rate_zone_time(void) { const int ZONE_0_HR = 100; const int ZONE_1_HR = 140; const int ZONE_2_HR = 160; const int ZONE_3_HR = 180; int32_t hr_zone_time_s[HRZoneCount]; cl_assert(
); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 0); prv_put_bpm_event(ZONE_1_HR, HRMQuality_Good); prv_inc_time(10); prv_put_bpm_event(ZONE_1_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 0); prv_inc_time(10); prv_put_bpm_event(ZONE_2_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 0); prv_inc_time(10); prv_put_bpm_event(ZONE_3_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 10); prv_inc_time(10); prv_put_bpm_event(ZONE_0_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 10); prv_inc_time(10); prv_put_bpm_event(ZONE_1_HR, HRMQuality_Good); workout_service_get_current_workout_hr_zone_time(hr_zone_time_s); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 20); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 10); // Pause the workout. Don't accumulate time in zones cl_assert(workout_service_pause_workout(true)); prv_inc_time(10); prv_put_bpm_event(ZONE_3_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 20); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 10); prv_inc_time(10); prv_put_bpm_event(ZONE_1_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 20); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 10); // Unpause workout cl_assert(workout_service_pause_workout(false)); prv_inc_time(10); prv_put_bpm_event(ZONE_3_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 20); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 20); prv_inc_time(10); prv_put_bpm_event(ZONE_2_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 20); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 20); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 20); cl_assert(!workout_service_get_current_workout_hr_zone_time(NULL)); cl_assert(workout_service_stop_workout()); cl_assert(!workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); } // --------------------------------------
workout_service_start_workout(ActivitySessionType_Run)
<|repo_name|>pebble <|file_sep|>tests/fw/services/activity/test_workout_service.c <|fim_prefix|>-- // Open the app, start a workout, close the app. Make sure the HR stays on for // WORKOUT_ACTIVE_HR_SUBSCRIPTION_TS_EXPIRE void test_workout_service__app_open_close_active_workout(void) { // Put some time into the clock prv_inc_time(1 * SECONDS_PER_MINUTE); // Open the app, confirm that we are now subscribed with no end in sight workout_service_frontend_opened(); cl_assert_equal_b(s_hrm_subscribed, true); cl_assert_equal_i(s_hrm_expiration, 0); cl_assert(workout_service_start_workout(ActivitySessionType_Run)); workout_service_frontend_closed(); cl_assert_equal_b(s_hrm_subscribed, true); cl_assert_equal_i(s_hrm_expiration, SECONDS_PER_HOUR); } // --------------------------------------------------------------------------------------- // Open the app, start a workout, 30s, stop the workout. Make sure the HR turns off instantly // since workout wasn't valid (too short) void test_workout_service__app_open_close_ended_invalid_workout(void) { // Put some time into the clock prv_inc_time(1 * SECONDS_PER_MINUTE); // Open the app, confirm that we are now subscribed with no end in sight workout_service_frontend_opened(); cl_assert_equal_b(s_hrm_subscribed, true); cl_assert_equal_i(s_hrm_expiration, 0); prv_inc_time(1 * SECONDS_PER_MINUTE); cl_assert(workout_service_start_workout(ActivitySessionType_Run)); // Workout of 30 seconds duration. Should be invalid, not keep HR on after leaving prv_inc_time(30); cl_assert(workout_service_stop_workout()); workout_service_frontend_closed(); cl_assert_equal_b(s_hrm_subscribed, false); cl_assert_equal_i(s_hrm_expiration, 0); } // --------------------------------------------------------------------------------------- // Open the app, start a workout, 120s, stop the workout, 120s, close app. // Make sure the HR stays on for WORKOUT_ENDED_HR_SUBSCRIPTION_TS_EXPIRE - 120s void test_workout_service__app_open_close_valid_workout(void) { // Put some time into the clock prv_inc_time(1 * SECONDS_PER_MINUTE); // Open the app, confirm that we are now subscribed with no end in sight workout_service_frontend_opened(); cl_assert_equal_b(s_hrm_subscribed, true); cl_assert_equal_i(s_hrm_expiration, 0); prv_inc_time(1 * SECONDS_PER_MINUTE); cl_assert(workout_service_start_workout(ActivitySessionType_Run)); // Workout of 120 seconds duration. Should be valid prv_inc_time(2 * SECONDS_PER_MINUTE); cl_assert(workout_service_stop_workout()); prv_inc_time(2 * SECONDS_PER_MINUTE); workout_service_frontend_closed(); cl_assert_equal_b(s_hrm_subscribed, true); cl_assert_equal_i(s_hrm_expiration, 8 * SECONDS_PER_MINUTE); } // --------------------------------------------------------------------------------------- // Open the app, start a workout, 120s, stop the workout, 20 min, close app. // Make sure the HR turns off right after we leave the app. void test_workout_service__app_open_wait_close_valid_workout(void) { // Put some time into the clock prv_inc_time(1 * SECONDS_PER_MINUTE); // Open the app, confirm that we are now subscribed with no end in sight workout_service_frontend_opened(); cl_assert_equal_b(s_hrm_subscribed, true); cl_assert_equal_i(s_hrm_expiration, 0); prv_inc_time(1 * SECONDS_PER_MINUTE); cl_assert(workout_service_start_workout(ActivitySessionType_Run)); // Workout of 120 seconds duration. Should be valid prv_inc_time(2 * SECONDS_PER_MINUTE); cl_assert(workout_service_stop_workout()); // Wait 20 minutes. By this time, as soon as we leave the app, we should turn off the HR device. prv_inc_time(20 * SECONDS_PER_MINUTE); workout_service_frontend_closed(); cl_assert_equal_b(s_hrm_subscribed, false); cl_assert_equal_i(s_hrm_expiration, 0); } // --------------------------------------------------------------------------------------- void test_workout_service__heart_rate_zone_time(void) { const int ZONE_0_HR = 100; const int ZONE_1_HR = 140; const int ZONE_2_HR = 160; const int ZONE_3_HR = 180; int32_t hr_zone_time_s[HRZoneCount]; cl_assert(<|fim_suffix|>); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 0); prv_put_bpm_event(ZONE_1_HR, HRMQuality_Good); prv_inc_time(10); prv_put_bpm_event(ZONE_1_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 0); prv_inc_time(10); prv_put_bpm_event(ZONE_2_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 0); prv_inc_time(10); prv_put_bpm_event(ZONE_3_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 0); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 10); prv_inc_time(10); prv_put_bpm_event(ZONE_0_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 10); prv_inc_time(10); prv_put_bpm_event(ZONE_1_HR, HRMQuality_Good); workout_service_get_current_workout_hr_zone_time(hr_zone_time_s); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 20); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 10); // Pause the workout. Don't accumulate time in zones cl_assert(workout_service_pause_workout(true)); prv_inc_time(10); prv_put_bpm_event(ZONE_3_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 20); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 10); prv_inc_time(10); prv_put_bpm_event(ZONE_1_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 20); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 10); // Unpause workout cl_assert(workout_service_pause_workout(false)); prv_inc_time(10); prv_put_bpm_event(ZONE_3_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 20); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 20); prv_inc_time(10); prv_put_bpm_event(ZONE_2_HR, HRMQuality_Good); cl_assert(workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone0], 10); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone1], 20); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone2], 20); cl_assert_equal_i(hr_zone_time_s[HRZone_Zone3], 20); cl_assert(!workout_service_get_current_workout_hr_zone_time(NULL)); cl_assert(workout_service_stop_workout()); cl_assert(!workout_service_get_current_workout_hr_zone_time(hr_zone_time_s)); } // --------------------------------------<|fim_middle|>workout_service_start_workout(ActivitySessionType_Run)<|endoftext|>
prefix_only
call_expression
tests/fw/graphics/test_graphics_draw_text.template.c
raw_text_single_line_ellipsis_clip_outside_nx.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_ellipsis_clip_outside_x); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_ellipsis_clip_outside_x.${BIT_DEPTH_NAME}.pbi")); // Word Wrap tests test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_across_ny); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_across_ny.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_across_ny_second_line); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_across_ny_second_line.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_across_y); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_across_y.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_across_y_second_line); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_across_y_second_line.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_across_nx); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_across_nx.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_across_x); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_across_x.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_outside_ny); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_outside_ny.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_outside_y); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_outside_y.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_outside_nx); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_outside_nx.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_outside_x); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_outside_x.${BIT_DEPTH_NAME}.pbi")); } #define RECT_TEXT_0_0 GRect(0, 0, 140, 1000) #define RECT_TEXT_2_0 GRect(2, 0, 140, 1000) void test_graphics_draw_text_${BIT_DEPTH_NAME}__clipping_letters(void) { GContext ctx; prv_setup_resources(); uint32_t gothic_18_handle = RESOURCE_ID_GOTHIC_18_BOLD; cl_assert(text_resources_init_font(0, gothic_18_handle, 0, &s_font_info)); test_graphics_context_init(&ctx, fb); // Test when clipping/drawing and text bounds are all at (0, 0) setup_test_aa_sw(&ctx, fb, RECT_TEXT_0_0, RECT_TEXT_0_0, false, 1); graphics_context_set_text_color(&ctx, GColorBlack); graphics_draw_text(&ctx, "jja", &s_font_info, RECT_TEXT_0_0, GTextOverflowModeTrailingEllipsis, GTextAlignmentLeft, NULL); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_jja00.${BIT_DEPTH_NAME}.pbi")); // Test when clipping/drawing are at (2, 0) and text bounds is at (0, 0)
setup_test_aa_sw(&ctx, fb, RECT_TEXT_2_0, RECT_TEXT_2_0, false, 1)
<|repo_name|>pebble <|file_sep|>tests/fw/graphics/test_graphics_draw_text.template.c <|fim_prefix|>raw_text_single_line_ellipsis_clip_outside_nx.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_ellipsis_clip_outside_x); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_ellipsis_clip_outside_x.${BIT_DEPTH_NAME}.pbi")); // Word Wrap tests test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_across_ny); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_across_ny.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_across_ny_second_line); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_across_ny_second_line.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_across_y); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_across_y.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_across_y_second_line); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_across_y_second_line.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_across_nx); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_across_nx.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_across_x); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_across_x.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_outside_ny); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_outside_ny.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_outside_y); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_outside_y.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_outside_nx); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_outside_nx.${BIT_DEPTH_NAME}.pbi")); test_graphics_context_reset(&ctx, fb); layer_set_update_proc(&layer, &draw_text_single_line_wordwrap_clip_outside_x); layer_render_tree(&canvas, &ctx); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_single_line_wordwrap_clip_outside_x.${BIT_DEPTH_NAME}.pbi")); } #define RECT_TEXT_0_0 GRect(0, 0, 140, 1000) #define RECT_TEXT_2_0 GRect(2, 0, 140, 1000) void test_graphics_draw_text_${BIT_DEPTH_NAME}__clipping_letters(void) { GContext ctx; prv_setup_resources(); uint32_t gothic_18_handle = RESOURCE_ID_GOTHIC_18_BOLD; cl_assert(text_resources_init_font(0, gothic_18_handle, 0, &s_font_info)); test_graphics_context_init(&ctx, fb); // Test when clipping/drawing and text bounds are all at (0, 0) setup_test_aa_sw(&ctx, fb, RECT_TEXT_0_0, RECT_TEXT_0_0, false, 1); graphics_context_set_text_color(&ctx, GColorBlack); graphics_draw_text(&ctx, "jja", &s_font_info, RECT_TEXT_0_0, GTextOverflowModeTrailingEllipsis, GTextAlignmentLeft, NULL); cl_check(gbitmap_pbi_eq(&ctx.dest_bitmap, "draw_text_jja00.${BIT_DEPTH_NAME}.pbi")); // Test when clipping/drawing are at (2, 0) and text bounds is at (0, 0) <|fim_suffix|><|fim_middle|>setup_test_aa_sw(&ctx, fb, RECT_TEXT_2_0, RECT_TEXT_2_0, false, 1)<|endoftext|>
masked_node
call_expression
src/fw/applib/app_smartstrap.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "applib/app_logging.h" #include "applib/app_smartstrap.h" #include "applib/app_smartstrap_private.h" #include "applib/applib_malloc.auto.h" #include "applib/event_service_client.h" #include "board/board.h" #include "process_state/app_state/app_state.h" #include "services/normal/accessory/smartstrap_attribute.h" #include "services/normal/accessory/smartstrap_connection.h" #include "services/normal/accessory/smartstrap_state.h" #include "system/passert.h" #include "util/mbuf.h" #define USE_SMARTSTRAP (CAPABILITY_HAS_ACCESSORY_CONNECTOR && !defined(RECOVERY_FW)) #if USE_SMARTSTRAP // Event handler //////////////////////////////////////////////////////////////////////////////// static void prv_app_smartstrap_event(PebbleEvent *e, void *context) { SmartstrapConnectionState *state = app_state_get_smartstrap_state(); PebbleSmartstrapEvent event = e->smartstrap; if (event.type == SmartstrapConnectionEvent) { // Drop this event if there's no handler registered if (state->handlers.availability_did_change) { const SmartstrapServiceId service_id = event.service_id; const bool is_available = (event.result == SmartstrapResultOk); state->handlers.availability_did_change(service_id, is_available); } } else { // All events other than SmartstrapConnectionEvent contain the attribute pointer SmartstrapAttribute *attr = event.attribute; PBL_ASSERTN(attr); if ((event.type == SmartstrapDataSentEvent) && state->handlers.did_write) { state->handlers.did_write(attr, event.result); } else if ((event.type == SmartstrapDataReceivedEvent) && state->handlers.did_read) { // 'attr' already points to the read buffer, so just need to cast it
; } else if ((event.type == SmartstrapNotifyEvent) && state->handlers.notified) { state->handlers.notified(attr); } sys_smartstrap_attribute_event_processed(attr); } } // Subscription functions //////////////////////////////////////////////////////////////////////////////// static bool prv_should_subscribe(void) { // We don't need to subscribe until either the app creates an attribute or subscribes an // availability_did_change handler. SmartstrapConnectionState *state = app_state_get_smartstrap_state(); return state->handlers.availability_did_change || state->num_attributes; } static void prv_state_init(void) { SmartstrapConnectionState *state = app_state_get_smartstrap_state(); if (state->is_initialized) { return; } state->event_info = (EventServiceInfo) { .type = PEBBLE_SMARTSTRAP_EVENT, .handler = prv_app_smartstrap_event }; event_service_client_subscribe(&state->event_info); state->timeout_ms = SMARTSTRAP_TIMEOUT_DEFAULT; sys_smartstrap_subscribe(); state->is_initialized = true; } static void prv_state_deinit(void) { SmartstrapConnectionState *state = app_state_get_smartstrap_state(); if (!state->is_initialized) { return; } state->is_initialized = false; event_service_client_unsubscribe(&state->event_info); sys_smartstrap_unsubscribe(); } #endif // Internal APIs //////////////////////////////////////////////////////////////////////////////// void app_smartstrap_cleanup(void) { #if USE_SMARTSTRAP prv_state_deinit(); #endif } // Exported APIs //////////////////////////////////////////////////////////////////////////////// SmartstrapResult app_smartstrap_subscribe(SmartstrapHandlers handlers) { #if USE_SMARTSTRAP SmartstrapConnectionState *state = app_state_get_smartstrap_state(); state->handlers = handlers; if (prv_should_subscribe()) { prv_state_init(); } return SmartstrapResultOk; #else return SmartstrapResultNotPresent; #endif } void app_smartstrap_unsubscribe(void) { #if USE_SMARTSTRAP SmartstrapConnectionState *state = app_state_get_smartstrap_state(); state->handlers = (SmartstrapHandlers) {0}; if (!prv_should_subscribe()) { prv_state_deinit(); } #endif } void app_smartstrap_set_timeout(uint16_t timeout_ms) { #if USE_SMARTSTRAP SmartstrapConnectionState *state = app_state_get_smartstrap_state(); state->timeout_ms = timeout_ms; #endif } SmartstrapAttribute *app_smartstrap_attribute_create(SmartstrapServiceId service_id, SmartstrapAttributeId attribute_id, size_t buffer_length) { #if USE_SMARTSTRAP if (!buffer_length) { return NULL; } uint8_t *buffer = applib_zalloc(buffer_length); if (!buffer) { return NULL; } if (!sys_smartstrap_attribute_register(service_id, attribute_id, buffer, buffer_length)) { applib_free(buffer); return NULL; } SmartstrapConnectionState *state = app_state_get_smartstrap_state(); state->num_attributes++; prv_state_init(); return (SmartstrapAttribute *)buffer; #else return NULL; #endif } void app_smartstrap_attribute_destroy(SmartstrapAttribute *attr) { #if USE_SMARTSTRAP SmartstrapConnectionState *state = app_state_get_smartstrap_state(); state->num_attributes--; if (!prv_should_subscribe()) { prv_state_deinit(); } sys_smartstrap_attribute_unregister(attr); #endif } bool app_smartstrap_service_is_available(SmartstrapServiceId service_id) { #if USE_SMARTSTRAP return sys_smartstrap_is_service_connected(service_id); #else return false; #endif } SmartstrapServiceId app_smartstrap_attribute_get_service_id(SmartstrapAttribute *attr) { #if USE_SMARTSTRAP SmartstrapServiceId service_id; sys_smartstrap_attribute_get_info(attr, &service_id, NULL, NULL); return service_id; #else return 0; #endif } SmartstrapAttributeId app_smartstrap_attribute_get_attribute_id(SmartstrapAttribute *attr) { #if USE_SMARTSTRAP SmartstrapServiceId attribute_id; sys_smartstrap_attribut
state->handlers.did_read(attr, event.result, (uint8_t *)attr, event.read_length)
<|repo_name|>pebble <|file_sep|>src/fw/applib/app_smartstrap.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "applib/app_logging.h" #include "applib/app_smartstrap.h" #include "applib/app_smartstrap_private.h" #include "applib/applib_malloc.auto.h" #include "applib/event_service_client.h" #include "board/board.h" #include "process_state/app_state/app_state.h" #include "services/normal/accessory/smartstrap_attribute.h" #include "services/normal/accessory/smartstrap_connection.h" #include "services/normal/accessory/smartstrap_state.h" #include "system/passert.h" #include "util/mbuf.h" #define USE_SMARTSTRAP (CAPABILITY_HAS_ACCESSORY_CONNECTOR && !defined(RECOVERY_FW)) #if USE_SMARTSTRAP // Event handler //////////////////////////////////////////////////////////////////////////////// static void prv_app_smartstrap_event(PebbleEvent *e, void *context) { SmartstrapConnectionState *state = app_state_get_smartstrap_state(); PebbleSmartstrapEvent event = e->smartstrap; if (event.type == SmartstrapConnectionEvent) { // Drop this event if there's no handler registered if (state->handlers.availability_did_change) { const SmartstrapServiceId service_id = event.service_id; const bool is_available = (event.result == SmartstrapResultOk); state->handlers.availability_did_change(service_id, is_available); } } else { // All events other than SmartstrapConnectionEvent contain the attribute pointer SmartstrapAttribute *attr = event.attribute; PBL_ASSERTN(attr); if ((event.type == SmartstrapDataSentEvent) && state->handlers.did_write) { state->handlers.did_write(attr, event.result); } else if ((event.type == SmartstrapDataReceivedEvent) && state->handlers.did_read) { // 'attr' already points to the read buffer, so just need to cast it <|fim_suffix|>; } else if ((event.type == SmartstrapNotifyEvent) && state->handlers.notified) { state->handlers.notified(attr); } sys_smartstrap_attribute_event_processed(attr); } } // Subscription functions //////////////////////////////////////////////////////////////////////////////// static bool prv_should_subscribe(void) { // We don't need to subscribe until either the app creates an attribute or subscribes an // availability_did_change handler. SmartstrapConnectionState *state = app_state_get_smartstrap_state(); return state->handlers.availability_did_change || state->num_attributes; } static void prv_state_init(void) { SmartstrapConnectionState *state = app_state_get_smartstrap_state(); if (state->is_initialized) { return; } state->event_info = (EventServiceInfo) { .type = PEBBLE_SMARTSTRAP_EVENT, .handler = prv_app_smartstrap_event }; event_service_client_subscribe(&state->event_info); state->timeout_ms = SMARTSTRAP_TIMEOUT_DEFAULT; sys_smartstrap_subscribe(); state->is_initialized = true; } static void prv_state_deinit(void) { SmartstrapConnectionState *state = app_state_get_smartstrap_state(); if (!state->is_initialized) { return; } state->is_initialized = false; event_service_client_unsubscribe(&state->event_info); sys_smartstrap_unsubscribe(); } #endif // Internal APIs //////////////////////////////////////////////////////////////////////////////// void app_smartstrap_cleanup(void) { #if USE_SMARTSTRAP prv_state_deinit(); #endif } // Exported APIs //////////////////////////////////////////////////////////////////////////////// SmartstrapResult app_smartstrap_subscribe(SmartstrapHandlers handlers) { #if USE_SMARTSTRAP SmartstrapConnectionState *state = app_state_get_smartstrap_state(); state->handlers = handlers; if (prv_should_subscribe()) { prv_state_init(); } return SmartstrapResultOk; #else return SmartstrapResultNotPresent; #endif } void app_smartstrap_unsubscribe(void) { #if USE_SMARTSTRAP SmartstrapConnectionState *state = app_state_get_smartstrap_state(); state->handlers = (SmartstrapHandlers) {0}; if (!prv_should_subscribe()) { prv_state_deinit(); } #endif } void app_smartstrap_set_timeout(uint16_t timeout_ms) { #if USE_SMARTSTRAP SmartstrapConnectionState *state = app_state_get_smartstrap_state(); state->timeout_ms = timeout_ms; #endif } SmartstrapAttribute *app_smartstrap_attribute_create(SmartstrapServiceId service_id, SmartstrapAttributeId attribute_id, size_t buffer_length) { #if USE_SMARTSTRAP if (!buffer_length) { return NULL; } uint8_t *buffer = applib_zalloc(buffer_length); if (!buffer) { return NULL; } if (!sys_smartstrap_attribute_register(service_id, attribute_id, buffer, buffer_length)) { applib_free(buffer); return NULL; } SmartstrapConnectionState *state = app_state_get_smartstrap_state(); state->num_attributes++; prv_state_init(); return (SmartstrapAttribute *)buffer; #else return NULL; #endif } void app_smartstrap_attribute_destroy(SmartstrapAttribute *attr) { #if USE_SMARTSTRAP SmartstrapConnectionState *state = app_state_get_smartstrap_state(); state->num_attributes--; if (!prv_should_subscribe()) { prv_state_deinit(); } sys_smartstrap_attribute_unregister(attr); #endif } bool app_smartstrap_service_is_available(SmartstrapServiceId service_id) { #if USE_SMARTSTRAP return sys_smartstrap_is_service_connected(service_id); #else return false; #endif } SmartstrapServiceId app_smartstrap_attribute_get_service_id(SmartstrapAttribute *attr) { #if USE_SMARTSTRAP SmartstrapServiceId service_id; sys_smartstrap_attribute_get_info(attr, &service_id, NULL, NULL); return service_id; #else return 0; #endif } SmartstrapAttributeId app_smartstrap_attribute_get_attribute_id(SmartstrapAttribute *attr) { #if USE_SMARTSTRAP SmartstrapServiceId attribute_id; sys_smartstrap_attribut<|fim_middle|>state->handlers.did_read(attr, event.result, (uint8_t *)attr, event.read_length)<|endoftext|>
masked_node
argument_list
tests/fw/services/blob_db/test_notif_db.c
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "clar.h" #include "util/uuid.h" #include "services/normal/filesystem/pfs.h" #include "services/normal/blob_db/notif_db.h" #include "services/normal/notifications/notification_storage.h" // Fixture //////////////////////////////////////////////////////////////// // Fakes //////////////////////////////////////////////////////////////// #include "fake_spi_flash.h" #include "fake_system_task.h" #include "fake_kernel_services_notifications.h" // Stubs //////////////////////////////////////////////////////////////// #include "stubs_analytics.h" #include "stubs_hexdump.h" #include "stubs_layout_layer.h" #include "stubs_logging.h" #include "stubs_mutex.h" #include "stubs_passert.h" #include "stubs_pbl_malloc.h" #include "stubs_prompt.h" #include "stubs_rand_ptr.h" #include "stubs_sleep.h" #include "stubs_task_watchdog.h" void test_notif_db__initialize(void) { fake_spi_flash_init(0, 0x1000000); pfs_init(false); notification_storage_reset(); } void test_notif_db__cleanup(void) { } void test_notif_db__get_length(void) { SerializedTimelineItemHeader hdr = { .common = { .ancs_uid = 1, .layout = 0, .flags = 0, .timestamp = 0, }, }; uuid_generate(&hdr.common.id); cl_assert_equal_i(notif_db_insert((uint8_t *)&hdr, UUID_SIZE, (uint8_t *)&hdr, sizeof(hdr)), 0); cl_assert_equal_i(notif_db_get_len((uint8_t *)&hdr, UUID_SIZE), sizeof(hdr)); } void test_notif_db__insert_remove(void) { SerializedTimelineItemHeader hdr = { .common = { .ancs_uid = 1, .layout = 0, .flags = 0, .timestamp = 0, }, }; uuid_generate(&hdr.common.id); cl_assert_equal_i(notif_db_insert((uint8_t *)&hdr, UUID_SIZE, (uint8_t *)&hdr, sizeof(hdr)), 0); cl_assert_equal_i(notif_db_delete((uint8_t *)&hdr, UUID_SIZE), 0); cl_assert_equal_i(notif_db_get_len((uint8_t *)&hdr, UUID_SIZE), 0); } void test_notif_db__flush(void) { SerializedTimelineItemHeader hdr1 = { .common = { .ancs_uid = 1, .layout = 0, .flags = 0, .timestamp = 0, }, }; uuid_generate(&hdr1.common.id); SerializedTimelineItemHeader hdr2 = { .common = { .ancs_uid = 1, .layout = 0, .flags = 0, .timestamp = 0, }, }; uuid_generate(&hdr2.common.id); SerializedTimelineItemHeader hdr3 = { .common = { .ancs_uid = 1, .layout = 0, .flags = 0, .timestamp = 0, }, }; uuid_generate(&hdr3.common.id); cl_assert_equal_i(notif_db_insert((uint8_t *)&hdr1, UUID_SIZE, (uint8_t *)&hdr1, sizeof(hdr1)), 0); cl_assert_equal_i(notif_db_insert((uint8_t *)&hdr2, UUID_SIZE, (uint8_t *)&hdr2, sizeof(hdr2)), 0); cl_assert_equal_i(notif_db_insert
, 0); cl_assert_equal_i(notif_db_flush(), 0); fake_system_task_callbacks_invoke_pending(); cl_assert_equal_i(notif_db_get_len((uint8_t *)&hdr1, UUID_SIZE), 0); cl_assert_equal_i(notif_db_get_len((uint8_t *)&hdr2, UUID_SIZE), 0); cl_assert_equal_i(notif_db_get_len((uint8_t *)&hdr3, UUID_SIZE), 0); }
((uint8_t *)&hdr3, UUID_SIZE, (uint8_t *)&hdr3, sizeof(hdr3))
<|repo_name|>pebble <|file_sep|>tests/fw/services/blob_db/test_notif_db.c <|fim_prefix|>/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "clar.h" #include "util/uuid.h" #include "services/normal/filesystem/pfs.h" #include "services/normal/blob_db/notif_db.h" #include "services/normal/notifications/notification_storage.h" // Fixture //////////////////////////////////////////////////////////////// // Fakes //////////////////////////////////////////////////////////////// #include "fake_spi_flash.h" #include "fake_system_task.h" #include "fake_kernel_services_notifications.h" // Stubs //////////////////////////////////////////////////////////////// #include "stubs_analytics.h" #include "stubs_hexdump.h" #include "stubs_layout_layer.h" #include "stubs_logging.h" #include "stubs_mutex.h" #include "stubs_passert.h" #include "stubs_pbl_malloc.h" #include "stubs_prompt.h" #include "stubs_rand_ptr.h" #include "stubs_sleep.h" #include "stubs_task_watchdog.h" void test_notif_db__initialize(void) { fake_spi_flash_init(0, 0x1000000); pfs_init(false); notification_storage_reset(); } void test_notif_db__cleanup(void) { } void test_notif_db__get_length(void) { SerializedTimelineItemHeader hdr = { .common = { .ancs_uid = 1, .layout = 0, .flags = 0, .timestamp = 0, }, }; uuid_generate(&hdr.common.id); cl_assert_equal_i(notif_db_insert((uint8_t *)&hdr, UUID_SIZE, (uint8_t *)&hdr, sizeof(hdr)), 0); cl_assert_equal_i(notif_db_get_len((uint8_t *)&hdr, UUID_SIZE), sizeof(hdr)); } void test_notif_db__insert_remove(void) { SerializedTimelineItemHeader hdr = { .common = { .ancs_uid = 1, .layout = 0, .flags = 0, .timestamp = 0, }, }; uuid_generate(&hdr.common.id); cl_assert_equal_i(notif_db_insert((uint8_t *)&hdr, UUID_SIZE, (uint8_t *)&hdr, sizeof(hdr)), 0); cl_assert_equal_i(notif_db_delete((uint8_t *)&hdr, UUID_SIZE), 0); cl_assert_equal_i(notif_db_get_len((uint8_t *)&hdr, UUID_SIZE), 0); } void test_notif_db__flush(void) { SerializedTimelineItemHeader hdr1 = { .common = { .ancs_uid = 1, .layout = 0, .flags = 0, .timestamp = 0, }, }; uuid_generate(&hdr1.common.id); SerializedTimelineItemHeader hdr2 = { .common = { .ancs_uid = 1, .layout = 0, .flags = 0, .timestamp = 0, }, }; uuid_generate(&hdr2.common.id); SerializedTimelineItemHeader hdr3 = { .common = { .ancs_uid = 1, .layout = 0, .flags = 0, .timestamp = 0, }, }; uuid_generate(&hdr3.common.id); cl_assert_equal_i(notif_db_insert((uint8_t *)&hdr1, UUID_SIZE, (uint8_t *)&hdr1, sizeof(hdr1)), 0); cl_assert_equal_i(notif_db_insert((uint8_t *)&hdr2, UUID_SIZE, (uint8_t *)&hdr2, sizeof(hdr2)), 0); cl_assert_equal_i(notif_db_insert<|fim_suffix|>, 0); cl_assert_equal_i(notif_db_flush(), 0); fake_system_task_callbacks_invoke_pending(); cl_assert_equal_i(notif_db_get_len((uint8_t *)&hdr1, UUID_SIZE), 0); cl_assert_equal_i(notif_db_get_len((uint8_t *)&hdr2, UUID_SIZE), 0); cl_assert_equal_i(notif_db_get_len((uint8_t *)&hdr3, UUID_SIZE), 0); } <|fim_middle|>((uint8_t *)&hdr3, UUID_SIZE, (uint8_t *)&hdr3, sizeof(hdr3))<|endoftext|>